From 795722e0dc55a6f18a278f594a12bc4ec42d8ebe Mon Sep 17 00:00:00 2001 From: Aleksandar Manukov Date: Sat, 15 Dec 2018 17:25:11 +0200 Subject: [PATCH 001/312] Add bootstrap-colorpicker@2.5.3 --- .../bootstrap-colorpicker@2.5.3-tests.ts | 0 types/bootstrap-colorpicker@2.5.3/index.d.ts | 267 ++++++++++++++++++ .../bootstrap-colorpicker@2.5.3/tsconfig.json | 22 ++ types/bootstrap-colorpicker@2.5.3/tslint.json | 1 + 4 files changed, 290 insertions(+) create mode 100644 types/bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts create mode 100644 types/bootstrap-colorpicker@2.5.3/index.d.ts create mode 100644 types/bootstrap-colorpicker@2.5.3/tsconfig.json create mode 100644 types/bootstrap-colorpicker@2.5.3/tslint.json diff --git a/types/bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts b/types/bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/bootstrap-colorpicker@2.5.3/index.d.ts b/types/bootstrap-colorpicker@2.5.3/index.d.ts new file mode 100644 index 0000000000..222b939b89 --- /dev/null +++ b/types/bootstrap-colorpicker@2.5.3/index.d.ts @@ -0,0 +1,267 @@ +// Type definitions for bootstrap-colorpicker 2.5.3 +// Project: https://github.com/farbelous/bootstrap-colorpicker/tree/v2.x +// Definitions by: Aleksandar Manukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type ColorPickerAlignOptions = 'right' | 'left'; + +type ColorPickerEvents = 'create' | + 'showPicker' | + 'hidePicker' | + 'changeColor' | + 'disable' | + 'enable' | + 'destroy' + +/** + * You can set colorpicker options either as a plugin parameter or data-* attributes + */ +interface ColorPickerOptions { + /** + * If not false, forces the color format to be hex, rgb or rgba, otherwise the format is automatically detected. + * + * Default: false + */ + format: string; + + /** + * If not false, sets the color to this value. + * + * Default: false + */ + color: string; + + /** + * If not false, the picker will be contained inside this element, otherwise it will be appended to the document body. + * + * Default: false + */ + container: string | JQuery; + + /** + * Children selector for the component or element that trigger the colorpicker and which background color will change (needs an inner element). + * + * Default: '.add-on, .input-group-addon' + */ + component: string | JQuery; + + /** + * Children selector for the input that will store the picker selected value. + * + * Default: 'input' + */ + input: string | JQuery; + + /** + * If true, put a '#' (number sign) before hex strings. + * + * Default: true + */ + hexNumberSignPrefix: boolean; + + /** + * If true, the hue and alpha channel bars will be rendered horizontally, above the saturation selector. + * + * Default: false + */ + horizontal: boolean; + + /** + * If true, forces to show the colorpicker as an inline element. + * + * Default: false + */ + inline: boolean; + + /** + * Vertical sliders configuration (read source code if you really need to tweak this). + */ + sliders: object; + + /** + * Horizontal sliders configuration (read source code if you really need to tweak this). + */ + slidersHorz: object; + + /** + * Customizes the default colorpicker HTML template. + */ + template: string; + + /** + * By default, the colorpicker is aligned to the right of the input. If you need to switch it to the left, set align to 'left'. + * + * Default: 'right' + */ + align: ColorPickerAlignOptions; + + /** + * Adds this class to the colorpicker widget. + * + * Default: null + */ + customClass: string; + + /** + * List of pre selected colors (hex format). If you choose one of these colors, the alias is returned instead of the hex code. + * + * Default: null + */ + colorSelectors: object; + + /** + * Fallback color string that will be applied when the color failed to be parsed. If null, it will keep the current color if any. + * + * Default: null + */ + fallbackColor: string; + + /** + * Fallback color format (e.g. when not specified or for alias mode, when selecting non aliased colors) + * + * Default: hex + */ + fallbackFormat: string; +} + +interface Color { + colors: {}; + fallbackFormat: string; + fallbackValue: string; + hexNumberSignPrefix: boolean; + origFormat: string; + predefinedColors: {}; + value: { + h: number; + s: number; + b: number; + a: number; + } + + /** + * Set a new color. The value is parsed and tries to do a quess on the format. + */ + setColor(value: string): void; + + /** + * Set the HUE with a value between 0 and 1. + */ + setHue(value: number): void; + + /** + * Set the saturation with a value between 0 and 1. + */ + setSaturation(value: number): void; + + /** + * Set the brightness with a value between 0 and 1. + */ + setBrightness(value: number): void; + + /** + * Set the transparency with a value between 0 and 1. + */ + setAlpha(value: number): void; + + /** + * Returns a hash with red, green, blue and alpha. + */ + toRGB(): string; + + /** + * Returns a string with HEX format for the current color. + */ + toHex(): string; + + /** + * Returns a hash with HSLA values. + */ + toHSL(): string; +} + +interface ColorPicker { + color: Color; + component: boolean; + container: boolean; + disabled: boolean; + element: JQuery; + format: string; + input: JQuery; + options: ColorPickerOptions; + picker: JQuery; +} + +interface ColorPickerEventObject { + +} + +interface JQuery { + /** + * Initializes an colorpicker. + */ + colorpicker(): JQuery; + + /** + * Initializes an colorpicker. + */ + colorpicker(options: ColorPickerOptions): JQuery; + + /** + * Gets the value from the input or the data attribute (if has no input), otherwise returns the default value, which defaults to #000000 if not specified. + */ + colorpicker(methodName: 'getValue', defaultValue: string): string; + + /** + * Set a new value for the color picker (also updates everything). Triggers 'changeColor' event. + */ + colorpicker(methodName: 'setValue', value: any): any; + + /** + * Show the color picker + */ + colorpicker(methodName: 'show'): void; + + /** + * Hide the color picker + */ + colorpicker(methodName: 'hide'): void; + + /** + * Updates the color picker's position relative to the element + */ + colorpicker(methodName: 'reposition'): void; + + /** + * Refreshes the widget colors (this is done automatically) + */ + colorpicker(methodName: 'update'): void; + + /** + * Enable the color picker. + */ + colorpicker(methodName: 'enable'): void; + + /** + * Disable the color picker. + */ + colorpicker(methodName: 'disable'): void; + + /** + * Destroys the colorpicker widget and unbind all .colorpicker events from the element and component + */ + colorpicker(methodName: 'destroy'): void; + + /** + * Access to the colorpicker API directly + */ + data(methodName: 'colorpicker'): ColorPicker; + + off(events: ColorPickerEvents, selector?: string, handler?: (event: ColorPickerEventObject) => any): JQuery; + off(events: ColorPickerEvents, handler: (event: ColorPickerEventObject) => any): JQuery; + + on(events: ColorPickerEvents, selector: string, data: any, handler?: (event: ColorPickerEventObject) => any): JQuery; + on(events: ColorPickerEvents, selector: string, handler: (event: ColorPickerEventObject) => any): JQuery; + on(events: ColorPickerEvents, handler: (event: ColorPickerEventObject) => any): JQuery; +} \ No newline at end of file diff --git a/types/bootstrap-colorpicker@2.5.3/tsconfig.json b/types/bootstrap-colorpicker@2.5.3/tsconfig.json new file mode 100644 index 0000000000..61299349f7 --- /dev/null +++ b/types/bootstrap-colorpicker@2.5.3/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-colorpicker@2.5.3-tests.ts" + ] +} diff --git a/types/bootstrap-colorpicker@2.5.3/tslint.json b/types/bootstrap-colorpicker@2.5.3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bootstrap-colorpicker@2.5.3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c8a1eeb459f2717f8482ffb2e77cba1be61dbac2 Mon Sep 17 00:00:00 2001 From: Aleksandar Manukov <34056917+aleksandar-manukov@users.noreply.github.com> Date: Sat, 15 Dec 2018 17:55:15 +0200 Subject: [PATCH 002/312] Rename bootstrap-colorpicker@2.5.3 to bootstrap-colorpicker@2.x --- .../bootstrap-colorpicker@2.x-tests.ts} | 0 .../index.d.ts | 0 .../tsconfig.json | 0 .../tslint.json | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename types/{bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts => bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts} (100%) rename types/{bootstrap-colorpicker@2.5.3 => bootstrap-colorpicker@2.x}/index.d.ts (100%) rename types/{bootstrap-colorpicker@2.5.3 => bootstrap-colorpicker@2.x}/tsconfig.json (100%) rename types/{bootstrap-colorpicker@2.5.3 => bootstrap-colorpicker@2.x}/tslint.json (100%) diff --git a/types/bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts b/types/bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts similarity index 100% rename from types/bootstrap-colorpicker@2.5.3/bootstrap-colorpicker@2.5.3-tests.ts rename to types/bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts diff --git a/types/bootstrap-colorpicker@2.5.3/index.d.ts b/types/bootstrap-colorpicker@2.x/index.d.ts similarity index 100% rename from types/bootstrap-colorpicker@2.5.3/index.d.ts rename to types/bootstrap-colorpicker@2.x/index.d.ts diff --git a/types/bootstrap-colorpicker@2.5.3/tsconfig.json b/types/bootstrap-colorpicker@2.x/tsconfig.json similarity index 100% rename from types/bootstrap-colorpicker@2.5.3/tsconfig.json rename to types/bootstrap-colorpicker@2.x/tsconfig.json diff --git a/types/bootstrap-colorpicker@2.5.3/tslint.json b/types/bootstrap-colorpicker@2.x/tslint.json similarity index 100% rename from types/bootstrap-colorpicker@2.5.3/tslint.json rename to types/bootstrap-colorpicker@2.x/tslint.json From 52d5fd2d3303e378ffd7cca1bbbd9eacb28d81cb Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 12 Jan 2019 16:56:56 +0800 Subject: [PATCH 003/312] init with types --- types/redux-state-sync/index.d.ts | 58 +++++++++++++++++++ .../redux-state-sync-tests.ts | 0 types/redux-state-sync/tsconfig.json | 22 +++++++ types/redux-state-sync/tslint.json | 1 + 4 files changed, 81 insertions(+) create mode 100644 types/redux-state-sync/index.d.ts create mode 100644 types/redux-state-sync/redux-state-sync-tests.ts create mode 100644 types/redux-state-sync/tsconfig.json create mode 100644 types/redux-state-sync/tslint.json diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts new file mode 100644 index 0000000000..e71097df17 --- /dev/null +++ b/types/redux-state-sync/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for redux-state-sync 2.0 +// Project: https://github.com/AOHUA/redux-state-sync#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace ReduxStateSync; + +import { Store, Reducer, Middleware, Action, AnyAction } from "redux" +import BroadcastChannel from "broadcast-channel" + +export let lastUuid: number; +export const GET_INIT_STATE: string; +export const SEND_INIT_STATE: string; +export const RECEIVE_INIT_STATE: string; + +type Stamp = { + $uuid: string + $wuid: string +} +export type StampedAction = Stamp & AnyAction + +export interface Config { + channel?: string + predicate?: Function | null + blacklist?: Array + whitelist?: Array + broadcastChannelOption?: object | null +} + +export interface MessageListenerConfig { + channel: BroadcastChannel + dispatch: (action: AnyAction | StampedAction) => void + allowed: (type?: string) => boolean +} + +export const defaultConfig: Config; +export const WINDOW_STATE_SYNC_ID: string; +export let isMessageListenerCreated: boolean; + +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +export function getIniteState(): AnyAction; +export function sendIniteState(): AnyAction; +export function receiveIniteState(store: Store): AnyAction; +export function s4(): string; +export function guid(): string; + +export function generateUuidForAction(action: AnyAction): StampedAction +export function isActionAllowed (config: Config): (type?: any) => boolean +export function createMessageListener (config: MessageListenerConfig): void +export function createStateSyncMiddleware (config?: Config): Middleware +export function withReduxStateSync ( + appReducer: Reducer +): (state: any, action: AnyAction) => Reducer +export function initStateWithPrevTab ( + store: Store +): Store \ No newline at end of file diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/redux-state-sync/tsconfig.json b/types/redux-state-sync/tsconfig.json new file mode 100644 index 0000000000..e3c2cd0f00 --- /dev/null +++ b/types/redux-state-sync/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-state-sync-tests.ts" + ] +} diff --git a/types/redux-state-sync/tslint.json b/types/redux-state-sync/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/redux-state-sync/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 386844dbd9dc240ee99d0478acc4d8a8593829af Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 12 Jan 2019 22:57:58 +0800 Subject: [PATCH 004/312] add declare module --- types/redux-state-sync/index.d.ts | 99 +++++++++---------- .../redux-state-sync-tests.ts | 27 +++++ 2 files changed, 76 insertions(+), 50 deletions(-) diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts index e71097df17..51aec60404 100644 --- a/types/redux-state-sync/index.d.ts +++ b/types/redux-state-sync/index.d.ts @@ -1,58 +1,57 @@ // Type definitions for redux-state-sync 2.0 // Project: https://github.com/AOHUA/redux-state-sync#readme -// Definitions by: My Self +// Definitions by: MU AOHUA +// AntonioMendez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export as namespace ReduxStateSync; +declare module "redux-state-sync" { + import { Store, Reducer, Middleware, AnyAction } from "redux"; + import BroadcastChannel from "broadcast-channel"; -import { Store, Reducer, Middleware, Action, AnyAction } from "redux" -import BroadcastChannel from "broadcast-channel" + export let lastUuid: number; + export const GET_INIT_STATE: string; + export const SEND_INIT_STATE: string; + export const RECEIVE_INIT_STATE: string; -export let lastUuid: number; -export const GET_INIT_STATE: string; -export const SEND_INIT_STATE: string; -export const RECEIVE_INIT_STATE: string; + type Stamp = { + $uuid: string; + $wuid: string; + }; + export type StampedAction = Stamp & AnyAction; -type Stamp = { - $uuid: string - $wuid: string + export interface Config { + channel?: string; + predicate?: Function | null; + blacklist?: Array; + whitelist?: Array; + broadcastChannelOption?: object | null; + } + + export interface MessageListenerConfig { + channel: BroadcastChannel; + dispatch: (action: AnyAction | StampedAction) => void; + allowed: (type?: string) => boolean; + } + + export const defaultConfig: Config; + export const WINDOW_STATE_SYNC_ID: string; + export let isMessageListenerCreated: boolean; + + export function myMethod(a: string): string; + export function myOtherMethod(a: number): number; + + export function getIniteState(): AnyAction; + export function sendIniteState(): AnyAction; + export function receiveIniteState(store: Store): AnyAction; + export function s4(): string; + export function guid(): string; + + export function generateUuidForAction(action: AnyAction): StampedAction; + export function isActionAllowed(config: Config): (type?: any) => boolean; + export function createMessageListener(config: MessageListenerConfig): void; + export function createStateSyncMiddleware(config?: Config): Middleware; + export function withReduxStateSync( + appReducer: Reducer + ): (state: any, action: AnyAction) => Reducer; + export function initStateWithPrevTab(store: Store): Store; } -export type StampedAction = Stamp & AnyAction - -export interface Config { - channel?: string - predicate?: Function | null - blacklist?: Array - whitelist?: Array - broadcastChannelOption?: object | null -} - -export interface MessageListenerConfig { - channel: BroadcastChannel - dispatch: (action: AnyAction | StampedAction) => void - allowed: (type?: string) => boolean -} - -export const defaultConfig: Config; -export const WINDOW_STATE_SYNC_ID: string; -export let isMessageListenerCreated: boolean; - -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; - -export function getIniteState(): AnyAction; -export function sendIniteState(): AnyAction; -export function receiveIniteState(store: Store): AnyAction; -export function s4(): string; -export function guid(): string; - -export function generateUuidForAction(action: AnyAction): StampedAction -export function isActionAllowed (config: Config): (type?: any) => boolean -export function createMessageListener (config: MessageListenerConfig): void -export function createStateSyncMiddleware (config?: Config): Middleware -export function withReduxStateSync ( - appReducer: Reducer -): (state: any, action: AnyAction) => Reducer -export function initStateWithPrevTab ( - store: Store -): Store \ No newline at end of file diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts index e69de29bb2..d23c317f09 100644 --- a/types/redux-state-sync/redux-state-sync-tests.ts +++ b/types/redux-state-sync/redux-state-sync-tests.ts @@ -0,0 +1,27 @@ +import { createStore, applyMiddleware, Action } from 'redux' +import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from 'redux-state-sync' + + +interface TestState { + a: number; + b: string; + c: string; +} +const config = { + channel: 'test', + predicate: () => {}, + blacklist: [], + whitelist: [], + broadcastChannelOption: {} +} +const middlewares = [ + createStateSyncMiddleware(config), +]; + +function rootReducer(state: TestState, action: Action): TestState { + return state; +} + +const store = createStore(withReduxStateSync(rootReducer), ['test'], ...applyMiddleware(middlewares)) +initStateWithPrevTab(store); + From 555156a64fcc173a2082dc33e5be0981ce53a455 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 12 Jan 2019 23:08:34 +0800 Subject: [PATCH 005/312] add strictFunctionTypes --- types/redux-state-sync/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/redux-state-sync/tsconfig.json b/types/redux-state-sync/tsconfig.json index e3c2cd0f00..e2c1dcbede 100644 --- a/types/redux-state-sync/tsconfig.json +++ b/types/redux-state-sync/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From ceba520e34406c97f96ae25821c74014347e6af8 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 12 Jan 2019 23:40:17 +0800 Subject: [PATCH 006/312] fix lint --- types/redux-state-sync/index.d.ts | 94 +++++++++---------- .../redux-state-sync-tests.ts | 25 +++-- 2 files changed, 57 insertions(+), 62 deletions(-) diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts index 51aec60404..329f56908b 100644 --- a/types/redux-state-sync/index.d.ts +++ b/types/redux-state-sync/index.d.ts @@ -4,54 +4,52 @@ // AntonioMendez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "redux-state-sync" { - import { Store, Reducer, Middleware, AnyAction } from "redux"; - import BroadcastChannel from "broadcast-channel"; +import { Store, Reducer, Middleware, AnyAction } from "redux"; +import BroadcastChannel from "broadcast-channel"; - export let lastUuid: number; - export const GET_INIT_STATE: string; - export const SEND_INIT_STATE: string; - export const RECEIVE_INIT_STATE: string; +export let lastUuid: number; +export const GET_INIT_STATE: string; +export const SEND_INIT_STATE: string; +export const RECEIVE_INIT_STATE: string; - type Stamp = { - $uuid: string; - $wuid: string; - }; - export type StampedAction = Stamp & AnyAction; - - export interface Config { - channel?: string; - predicate?: Function | null; - blacklist?: Array; - whitelist?: Array; - broadcastChannelOption?: object | null; - } - - export interface MessageListenerConfig { - channel: BroadcastChannel; - dispatch: (action: AnyAction | StampedAction) => void; - allowed: (type?: string) => boolean; - } - - export const defaultConfig: Config; - export const WINDOW_STATE_SYNC_ID: string; - export let isMessageListenerCreated: boolean; - - export function myMethod(a: string): string; - export function myOtherMethod(a: number): number; - - export function getIniteState(): AnyAction; - export function sendIniteState(): AnyAction; - export function receiveIniteState(store: Store): AnyAction; - export function s4(): string; - export function guid(): string; - - export function generateUuidForAction(action: AnyAction): StampedAction; - export function isActionAllowed(config: Config): (type?: any) => boolean; - export function createMessageListener(config: MessageListenerConfig): void; - export function createStateSyncMiddleware(config?: Config): Middleware; - export function withReduxStateSync( - appReducer: Reducer - ): (state: any, action: AnyAction) => Reducer; - export function initStateWithPrevTab(store: Store): Store; +export interface Stamp { + $uuid: string; + $wuid: string; } +export type StampedAction = Stamp & AnyAction; + +export interface Config { + channel?: string; + predicate?: (type?: string) => boolean | null; + blacklist?: string[]; + whitelist?: string[]; + broadcastChannelOption?: object | null; +} + +export interface MessageListenerConfig { + channel: BroadcastChannel; + dispatch: (action: AnyAction | StampedAction) => void; + allowed: (type?: string) => boolean; +} + +export const defaultConfig: Config; +export const WINDOW_STATE_SYNC_ID: string; +export let isMessageListenerCreated: boolean; + +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +export function getIniteState(): AnyAction; +export function sendIniteState(): AnyAction; +export function receiveIniteState(store: Store): AnyAction; +export function s4(): string; +export function guid(): string; + +export function generateUuidForAction(action: AnyAction): StampedAction; +export function isActionAllowed(config: Config): (type?: any) => boolean; +export function createMessageListener(config: MessageListenerConfig): void; +export function createStateSyncMiddleware(config?: Config): Middleware; +export function withReduxStateSync( + appReducer: Reducer +): (state: any, action: AnyAction) => Reducer; +export function initStateWithPrevTab(store: Store): Store; diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts index d23c317f09..0e9207cea0 100644 --- a/types/redux-state-sync/redux-state-sync-tests.ts +++ b/types/redux-state-sync/redux-state-sync-tests.ts @@ -1,27 +1,24 @@ -import { createStore, applyMiddleware, Action } from 'redux' -import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from 'redux-state-sync' - +import { createStore, applyMiddleware, Action } from 'redux'; +import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from 'redux-state-sync'; interface TestState { a: number; b: string; c: string; } -const config = { - channel: 'test', - predicate: () => {}, - blacklist: [], - whitelist: [], - broadcastChannelOption: {} -} const middlewares = [ - createStateSyncMiddleware(config), + createStateSyncMiddleware({ + channel: 'test', + predicate: (type) => true, + blacklist: [], + whitelist: [], + broadcastChannelOption: {} + }), ]; function rootReducer(state: TestState, action: Action): TestState { return state; } - -const store = createStore(withReduxStateSync(rootReducer), ['test'], ...applyMiddleware(middlewares)) -initStateWithPrevTab(store); +const store = createStore(withReduxStateSync(rootReducer), ['test'], ...applyMiddleware(middlewares)); +initStateWithPrevTab(store); From 8176350042aa66987712a7337b0c7c24cb6eee03 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 12 Jan 2019 23:55:52 +0800 Subject: [PATCH 007/312] change to Double quotes --- types/redux-state-sync/redux-state-sync-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts index 0e9207cea0..17e73dd591 100644 --- a/types/redux-state-sync/redux-state-sync-tests.ts +++ b/types/redux-state-sync/redux-state-sync-tests.ts @@ -1,5 +1,5 @@ -import { createStore, applyMiddleware, Action } from 'redux'; -import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from 'redux-state-sync'; +import { createStore, applyMiddleware, Action } from "redux"; +import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from "redux-state-sync"; interface TestState { a: number; From af37e28143e3f0bc3b1f5d1841ceb221ffb89fa5 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sun, 13 Jan 2019 10:59:31 +0800 Subject: [PATCH 008/312] fix lint --- types/redux-state-sync/index.d.ts | 1 + types/redux-state-sync/package.json | 7 +++++++ types/redux-state-sync/redux-state-sync-tests.ts | 8 +++----- 3 files changed, 11 insertions(+), 5 deletions(-) create mode 100644 types/redux-state-sync/package.json diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts index 329f56908b..755d354707 100644 --- a/types/redux-state-sync/index.d.ts +++ b/types/redux-state-sync/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: MU AOHUA // AntonioMendez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 import { Store, Reducer, Middleware, AnyAction } from "redux"; import BroadcastChannel from "broadcast-channel"; diff --git a/types/redux-state-sync/package.json b/types/redux-state-sync/package.json new file mode 100644 index 0000000000..d39f9e8fc6 --- /dev/null +++ b/types/redux-state-sync/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "broadcast-channel": "^2.1.8", + "redux": "^4.0.1" + } +} diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts index 17e73dd591..3f5e689675 100644 --- a/types/redux-state-sync/redux-state-sync-tests.ts +++ b/types/redux-state-sync/redux-state-sync-tests.ts @@ -6,19 +6,17 @@ interface TestState { b: string; c: string; } -const middlewares = [ - createStateSyncMiddleware({ +const middleware = createStateSyncMiddleware({ channel: 'test', predicate: (type) => true, blacklist: [], whitelist: [], broadcastChannelOption: {} - }), -]; + }); function rootReducer(state: TestState, action: Action): TestState { return state; } -const store = createStore(withReduxStateSync(rootReducer), ['test'], ...applyMiddleware(middlewares)); +const store = createStore(withReduxStateSync(rootReducer), ['test'], applyMiddleware(middleware)); initStateWithPrevTab(store); From f45b084c08487b387b61b65b364d19df46e63097 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Mon, 14 Jan 2019 22:44:31 +0800 Subject: [PATCH 009/312] Added definitions for forge-apis Added definitions for forge-apis This is approved by its author Forge Partner Development team and I am part of that team myself --- types/forge-apis/README.md | 16 + types/forge-apis/forge-apis-tests.ts | 13 + types/forge-apis/index.d.ts | 25 + types/forge-apis/package.json | 38 ++ types/forge-apis/src/forge-apis.d.ts | 109 +++++ types/forge-apis/src/forge.d.ts | 99 ++++ types/forge-apis/src/viewer-extensions.d.ts | 66 +++ types/forge-apis/src/viewer.d.ts | 485 ++++++++++++++++++++ types/forge-apis/tsconfig.json | 24 + types/forge-apis/tslint.json | 79 ++++ 10 files changed, 954 insertions(+) create mode 100644 types/forge-apis/README.md create mode 100644 types/forge-apis/forge-apis-tests.ts create mode 100644 types/forge-apis/index.d.ts create mode 100644 types/forge-apis/package.json create mode 100644 types/forge-apis/src/forge-apis.d.ts create mode 100644 types/forge-apis/src/forge.d.ts create mode 100644 types/forge-apis/src/viewer-extensions.d.ts create mode 100644 types/forge-apis/src/viewer.d.ts create mode 100644 types/forge-apis/tsconfig.json create mode 100644 types/forge-apis/tslint.json diff --git a/types/forge-apis/README.md b/types/forge-apis/README.md new file mode 100644 index 0000000000..9da41d3d61 --- /dev/null +++ b/types/forge-apis/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/forge-apis` + +# Summary +This package contains type definitions for Forge Node.js SDK (https://github.com/Autodesk-Forge/forge-api-nodejs-client). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-apis + +Additional Details + * Last updated: Fri, 11 Jan 2019 10:39:13 GMT + * Dependencies: @types/three + * Global values: none + +# Credits +Forge Partner Development diff --git a/types/forge-apis/forge-apis-tests.ts b/types/forge-apis/forge-apis-tests.ts new file mode 100644 index 0000000000..e25c781890 --- /dev/null +++ b/types/forge-apis/forge-apis-tests.ts @@ -0,0 +1,13 @@ +import {AuthClientTwoLegged, AuthClientThreeLegged, BucketsApi, HubsApi, FoldersApi, DerivativesApi} from 'forge-apis' + +var authClientTwoLegged: AuthClientTwoLegged = new AuthClientTwoLegged("","",[]); + +var authClientThreeLegged: AuthClientThreeLegged = new AuthClientThreeLegged("","","",[]); + +var bucketsApi: BucketsApi = new BucketsApi(); + +var hubsApi: HubsApi = new HubsApi(); + +var foldersApi: FoldersApi = new FoldersApi(); + +var derivativesApi: DerivativesApi = new DerivativesApi(); diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts new file mode 100644 index 0000000000..8f984d633d --- /dev/null +++ b/types/forge-apis/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for Forge Node.js SDK +// Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client +// Definitions by: Autodesk Forge Partner Development +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +/// +/// +/// +/// diff --git a/types/forge-apis/package.json b/types/forge-apis/package.json new file mode 100644 index 0000000000..7ab6a26459 --- /dev/null +++ b/types/forge-apis/package.json @@ -0,0 +1,38 @@ +{ + "name": "forge-api.typescript", + "version": "0.0.1", + "homepage": "https://github.com/cyrillef/forge-api.typescript", + "author": "Cyrille Fauvel", + "contributors": [ + "Cyrille Fauvel " + ], + "repository": { + "type": "git", + "url": "git+https://github.com/cyrillef/forge-api.typescript.git" + }, + "bugs": { + "url": "https://github.com/cyrillef/forge-api.typescript/issues" + }, + "keywords": [ + "typescript", + "forge", + "autodesk", + "api" + ], + "engines": { + "node": ">=8.0.0" + }, + "license": "MIT", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsc" + }, + "dependencies": {}, + "devDependencies": { + "@types/three": "^0.93.15", + "typescript": "^3.2.1", + "typings": "^2.1.1" + }, + "optionalDependencies": {} +} diff --git a/types/forge-apis/src/forge-apis.d.ts b/types/forge-apis/src/forge-apis.d.ts new file mode 100644 index 0000000000..2ae2d8dde6 --- /dev/null +++ b/types/forge-apis/src/forge-apis.d.ts @@ -0,0 +1,109 @@ +// +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +declare module 'forge-apis' { + export class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); + + authenticate(): Promise; + getCredentials(): Autodesk.Forge.AuthToken; + setCredentials(credentials: Autodesk.Forge.AuthToken): void; + isAuthorized(): boolean; + } + + export class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; + } + + export interface ApiResponse { + body: any; + headers: any; + statusCode: number; + } + + export interface ApiError { + statusCode: number; + statusMessage: string; + } + + export class BucketsApi { + constructor(); + + createBucket(postBuckets: Object, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBuckets(options: Object, credentials: Autodesk.Forge.AuthToken): Promise; + } + + export class HubsApi { + constructor(); + + getHub(hubId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubs(opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubProjects(hubId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + } + + export class FoldersApi { + constructor(); + + getFolderContents(projectId: string, folderId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + } + + export interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; + } + + export interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; + } + + export interface JobPayloadOutput { + formats: JobPayloadItem[]; + } + + export interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }, + format?: string; + exportColor?: boolean; + exportFileStructure?: string; + } + + export class DerivativesApi { + constructor(); + + deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getFormats(opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getManifest(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getMetadata(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + getThumbnail(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; + } +} diff --git a/types/forge-apis/src/forge.d.ts b/types/forge-apis/src/forge.d.ts new file mode 100644 index 0000000000..2b126eac9e --- /dev/null +++ b/types/forge-apis/src/forge.d.ts @@ -0,0 +1,99 @@ +// +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +declare module Autodesk { + export module Forge { + export interface Credentials { + client_id: string; + client_secret: string; + grant_type: string; + scope?: string; + } + + export interface AuthToken { + access_token: string; + expires_in: number; + token_type: string; + refresh_token?: string; + } + + export module Dm { + export interface BucketResponse { + bucketKey: string; + bucketOwner: string; + createdDate: number; + permissions: { + access: string; + authId: string; + }[]; + policyKey: string; + } + + export interface ItemResponse { + data: any[]; + included: Item[]; + jsonapi: { + version: string; + }; + links: any; + } + + export interface Item { + attributes: { + createTime: string; + createUserId: string; + displayName: string; + extension: Object; + fileType: string; + lastModifiedTime: string; + lastModifiedUserId: string; + mimeType: string; + name: string; + storageSize: number; + versionNumber: number; + }; + id: string; + links: { + self: { + href: string; + }; + }; + relationships: { + derivatives: { + data: { + id: string; + }, + meta: { + link: { + href: string; + } + } + }, + item: any; + refs: any; + storage: { + data: { + id: string; + type: string; + } + }; + thumbnail: any; + }; + type: string; + } + } + } +} diff --git a/types/forge-apis/src/viewer-extensions.d.ts b/types/forge-apis/src/viewer-extensions.d.ts new file mode 100644 index 0000000000..4b5bf53a1f --- /dev/null +++ b/types/forge-apis/src/viewer-extensions.d.ts @@ -0,0 +1,66 @@ +// +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +/// + +declare module Autodesk { + export module Viewing { + export module Extensions { + export module Markups { + export module Core { + export class MarkupsCore extends Autodesk.Viewing.Extension { + duringEditMode: boolean; + duringViewMode: boolean; + + enterEditMode(): boolean; + leaveEditMode(): boolean; + changeEditMode(mode: EditMode): void; + hide(): boolean; + show(): boolean; + toggle(): boolean; + clear(): void; + generateData(): string; + generatePoints3d(): any; + allowNavigation(allow: boolean): void; + disableMarkupInteractions(disable: boolean): void; + } + + export class EditMode { + constructor(extension: Autodesk.Viewing.Extension); + } + + export class EditModeArrow extends EditMode { + } + + export class EditModeCircle extends EditMode { + } + + export class EditModeCloud extends EditMode { + } + + export class EditModeFreehand extends EditMode { + } + + export class EditModeRectangle extends EditMode { + } + + export class EditModeText extends EditMode { + } + } + } + } + } +} \ No newline at end of file diff --git a/types/forge-apis/src/viewer.d.ts b/types/forge-apis/src/viewer.d.ts new file mode 100644 index 0000000000..ca847ee2c1 --- /dev/null +++ b/types/forge-apis/src/viewer.d.ts @@ -0,0 +1,485 @@ +// +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +/// + +declare module Autodesk { + export module Viewing { + // events + export var ESCAPE_EVENT: string; + export var PROGRESS_UPDATE_EVENT: string; + export var FULLSCREEN_MODE_EVENT: string; + export var NAVIGATION_MODE_CHANGED_EVENT: string; + export var VIEWER_STATE_RESTORED_EVENT: string; + export var VIEWER_RESIZE_EVENT: string; + export var VIEWER_UNINITIALIZED: string; + export var MODEL_ROOT_LOADED_EVENT: string; + export var GEOMETRY_LOADED_EVENT: string; + export var TOOLBAR_CREATED_EVENT: string; + export var OBJECT_TREE_CREATED_EVENT: string; + export var OBJECT_TREE_UNAVAILABLE_EVENT: string; + export var MODEL_UNLOADED_EVENT: string; + export var SELECTION_CHANGED_EVENT: string; + export var AGGREGATE_SELECTION_CHANGED_EVENT: string; + export var ISOLATE_EVENT: string; + export var HIDE_EVENT: string; + export var SHOW_EVENT: string; + export var HIGHLIGHT_EVENT: string; + export var CAMERA_CHANGE_EVENT: string; + export var EXPLODE_CHANGE_EVENT: string; + export var CUTPLANES_CHANGE_EVENT: string; + export var TOOL_CHANGE_EVENT: string; + export var TOOLBAR_CREATED_EVENT: string; + export var RENDER_OPTION_CHANGED_EVENT: string; + export var LAYER_VISIBILITY_CHANGED_EVENT: string; + export var RESET_EVENT: string; + export var ANIMATION_READY_EVENT: string; + + export enum SelectionMode { + LEAF_OBJECT, + FIRST_OBJECT, + LAST_OBJECT + } + + export var theExtensionManager: ExtensionManager; + + export interface InitializerOptions { + env?: string; + language?: string; + webGLHelpLink?: string; + getAccessToken?(callback?: (accessToken: string, expires?: number) => void): void; + refreshToken?(callback?: (accessToken: string, expires?: number) => void): void; + } + + export function Initializer(options: InitializerOptions, callback?: () => void): void; + + export class Document { + static load(documentId: string, successCallback: (doc: Document) => void, errorCallback: (errorCode: number, errorMsg: string, messages: any[]) => void, accessControlProperties?: any): void; + static getSubItemsWithProperties(item: Object, properties: Properties, recursive: boolean): Object[]; + + acmSessionId: string; + + getRootItem(): Object; + getViewablePath(item: Object): string; + } + + export class Extension { + viewer: Autodesk.Viewing.Private.GuiViewer3D; + options: any; + constructor(viewer: Autodesk.Viewing.Private.GuiViewer3D, options: any); + + load(): boolean; + unload(): boolean; + } + + export class ExtensionManager { + registerExtension(extensionId: string, extension: any): boolean; + unregisterExtension(extensionId: string): boolean; + + getExtension(extensionId: string): any; + } + + export class InstanceTree { + maxDepth: number; + nodeAccess: InstanceTreeAccess; + numHidden: number; + numOff: number; + objectCount: number; + + enumNodeChildren(node: number|any, callback: (dbId: number) => void, recursive?: boolean): void; + enumNodeFragments(node: number|any, callback: (fragId: number) => void, recursive?: boolean): void; + getChildCount(dbId: number): number; + getNodeBox(dbId: number, nodeBox: Float32Array): void; + getNodeParentId(dbId: number): number; + getRootId(): number; + setFlagGlobal(flag: any, value: any): void; + setFlagNode(dbId: number, flag: any, value: any): boolean; + } + + export class InstanceTreeAccess { + children: any; + dbIdToIndex: any; + nameSuffixes: any; + names: any; + nodeBoxes: any; + nodes: any; + numNodes: number; + rootId: number; + strings: string[]; + visibleIds: number; + } + + export interface InstanceTreeNode { + dbId: number; + name: string; + fragments: number[]; + children: InstanceTreeNode[]; + } + + export class Model { + getBoundingBox(): THREE.Box3; + getBulkProperties(dbIds: number[], propFilter?: string[], successCallback?: (r: any) => void, errorCallback?: (err: any) => void): void; + getData(): any; + getFragmentList(): any; + getObjectTree(successCallback?: (result: InstanceTree) => void, errorCallback?: (err: any) => void): void; + getProperties(dbId: number, successCallback?: (r: PropertyResult) => void, errorCallback?: (err: any) => void): void; + getUnitScale(): number; + getUnitString(): number; + //search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; + search(text: string, successCallback: (r: number[]) => void, errorCallback?: (err: any) => void, attributeNames?: string[]): void; + clearThemingColors(): void; + + getInstanceTree(): InstanceTree; + visibilityManager: Private.VisibilityManager; + } + + export interface PropertyResult { + dbId: number; + externalId?: string; + name?: string; + properties: Property[]; + } + + export interface Property { + displayCategory: string; + displayName: string; + displayValue: string; + hidden: boolean; + type: number; + units: string; + } + + export class Navigation { + getCamera(): any; + getEyeVector(): THREE.Vector3; + getFovMin(): number; + getFovMax(): number; + getPivotPoint(): THREE.Vector3; + setPivotPoint(pivot: THREE.Vector3): void; + getPosition(): THREE.Vector3; + setPosition(pos: THREE.Vector3): void; + getTarget(): THREE.Vector3; + setTarget(target: THREE.Vector3): void; + getScreenViewport(): ClientRect; + setScreenViewport(viewport: ClientRect): void; + setView(position: THREE.Vector3, target: THREE.Vector3): void; + setCameraUpVector(up: THREE.Vector): void; + } + + export interface Properties { + type: string; + role: string; + } + + export class ToolController { + activateTool(name: string): boolean; + deactivateTool(name: string): boolean; + registerTool(tool: any): boolean; + deregisterTool(tool: any): boolean; + getToolNames(): string[]; + getActiveToolName (): string; + } + + export interface ToolInterface { + getCursor?(): string; + getName(): string; + getNames(): string[]; + register(): void; + deregister(): void; + activate(name: string, viewerApi?: Autodesk.Viewing.Private.GuiViewer3D): void; + deactivate(name: string): void; + update(): boolean; + handleSingleClick?(event: MouseEvent, button: number): boolean; + handleDoubleClick?(event: MouseEvent, button: number): boolean; + handleSingleTap?(event: Event): boolean; + handleDoubleTap?(event: Event): boolean; + handleKeyDown?(event: KeyboardEvent, keyCode: number): boolean; + handleKeyUp?(event: KeyboardEvent, keyCode: number): boolean; + handleWheelInput?(delta: number): boolean; + handleButtonDown?(event: MouseEvent, button: number): boolean; + handleButtonUp?(event: MouseEvent, button: number): boolean; + handleMouseMove?(event: MouseEvent): boolean; + handleGesture?(event: Event): boolean; + handleBlur?(event: Event): boolean; + handleResize?(): void; + } + + export class UnifiedCamera { + } + + export interface ContextMenuCallbackStatus { + hasHidden: boolean, + hasSelected: boolean, + hasVisible: boolean, + numSelected: number + } + + export interface ContextMenuItem { + target: () => void, + title: string + } + + export class Viewer3D { + id: number; + + clearSelection(): void; + clearThemingColors(model: any): void; + clientToWorld(point: THREE.Vector3): THREE.Vector3; + createViewCube(): void; + displayViewCube(display: boolean): void; + fitToView(objectIds?: number[], model?: Model): boolean; + getHiddenNodes(): number[]; + getIsolatedNodes(): number[]; + getSelection(): number[]; + getSelectionCount(): number; + getSelectionVisibility(): { hasVisible: boolean, hasHidden: boolean }; + getState(filter?: any): any; + hide(node: number | number[]): void; + hideById(node: number): void; + isolate(node: number | number[]): void; + isolateById(dbIds: number | number[]): void; + registerContextMenuCallback(id: string, callback: (menu: ContextMenuItem[], status: ContextMenuCallbackStatus) => void): void; + resize(): void; + restoreState(state: any, filter?: any, immediate?: boolean): boolean; + search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; + select(dbIds: number | number[]): void; + setCutPlanes(planes: THREE.Vector4[]): void; + setSelectionMode(mode: Autodesk.Viewing.SelectionMode): void; + setThemingColor(dbId: number, color: THREE.Vector4, model?: any): void; + setUp(config?: any): void; + setViewCube(face: string): void; + show(node: number | number[]): void; + showAll(): void; + tearDown(): void; + toggleSelect(dbid: number): void; + unregisterContextMenuCallback(id: string): void; + worldToClient(point: THREE.Vector3): THREE.Vector3; + } + + export class ViewingUtilities { + getHitPoint(x: number, y: number): THREE.Vector3; + } + + export module Private { + + export function getHtmlTemplate(url: string, callback: (error: string, content: string) => void): void; + + export class GuiViewer3D extends Viewer3D { + constructor(container: HTMLElement, config?: Object); + + canvas: HTMLCanvasElement; + container: Element; + toolController: Viewing.ToolController; + impl: Viewer3DImpl; + model: Model; + navigation: Navigation; + + getCamera(): UnifiedCamera; + getToolbar(create: boolean): UI.ToolBar; + initialize(): any; + load(urn: string, sharedPropertyDbPath?: string, onSuccesfullCallback?: () => void, onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; + loadModel(urn: string, options?: any, onSuccesfullCallback?: () => void, onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; + start(path?: string, options?: Object): any; + finish(): any; + setUsePivotAlways(value: boolean):any; + + setGroundShadow (param: boolean):void ; + setGroundReflection (param: boolean):void ; + setOptimizeNavigation (param: boolean):void ; + setQualityLevel (useSAO: boolean, useFXAA: boolean):void ; + + loadExtension(extensionId: string, options?: Object): boolean; + unloadExtension(extensionId: string): boolean; + getExtension(extensionId: string): Extension; + + addPanel(panel: UI.DockingPanel): boolean; + removePanel(panel: UI.DockingPanel): boolean; + resizePanels(options: any): void; + + addEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; + removeEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; + + } + + export interface HitTestResult { + dbId: number; + face: THREE.Face3; + fragId: number; + intersectPoint: THREE.Vector3; + model: Autodesk.Viewing.Model; + } + + export class HudMessage { + static displayMessage(container: Element, messageSpec: { + msgTitleKey: string, + msgTitleDefault?: string, + messageKey: string, + messageDefaultValue?: string, + buttonText?: string, + checkboxChecked?: boolean + }, closeCallback?: (event: any) => void, buttonCallback?: (event: any) => void, checkboxCallback?: (event: any) => void): void; + + static dismiss(): boolean; + } + + export class Viewer3DImpl { + constructor(thecanvas: any, theapi: any); + + visibilityManager: VisibilityManager; + + clientToViewport(clientX: number, clientY: number): THREE.Vector3; + hitTest(clientX: number, clientY: number, ignoreTransparent: boolean): HitTestResult; + hitTestViewport(vpVec: THREE.Vector3, ignoreTransparent: boolean): HitTestResult; + initialize(): void; + setLightPreset(index: number, force?: boolean): void; + viewportToClient(viewportX: number, viewportY: number): THREE.Vector3; + + getMaterials(): any; + getRenderProxy(model: Model, fragId: number): any; + sceneUpdated(param: boolean): void; + } + + export class VisibilityManager { + constructor(viewerImpl: any, model: any); + + getHiddenNodes(): any; + getInstanceTree(): InstanceTree; + getIsolatedNodes(): any; + hide(node: number | Object): void; + isNodeVisible(dbId: number): boolean; + isolate(node: number | Object): void; + isolateMultiple(nodeList: any[]): void; + isolateNone(): void; + setAllVisibility(visible: boolean): void; + setVisibilityOnNode(node: number | Object, visible: boolean): void; + setNodeOff(node: number | Object, isOff: boolean): void; + show(node: number | Object): void; + toggleVisibility(node: number | Object): void; + updateNodeVisibilityTracking(node: number | Object, visible: boolean): void; + } + } + + export module UI { + export class Control { + container: HTMLElement; + + getId(): string; + isCollapsed(): boolean; + setCollapsed(collappsed: boolean): boolean; + setToolTip(toolTipText: string): void; + getToolTip(): string; + isVisible(): boolean; + setVisible(visible: boolean): boolean; + } + + export class Button extends Control { + constructor(id: string, options?: any); + + setIcon(iconClass: string): void; + getState(): Autodesk.Viewing.UI.Button.State; + setState(state: Autodesk.Viewing.UI.Button.State): boolean; + onClick(event: MouseEvent): void; + onMouseOver(event: MouseEvent): void; + onMouseOut(event: MouseEvent): void; + } + + // NOTE: TypeScript doesn't support enum inside class + module Button { + export enum State { ACTIVE, INACTIVE, DISABLED } + } + + export class ControlGroup extends Control { + constructor(id: string, options?: any); + + addClass(name: string): void; + addControl(control: Control, options?: any): any; + removeControl(control: Control | string): any; + getControl(controlId: string): Control; + getNumberOfControls(): number; + } + + export class ToolBar extends ControlGroup { + addEventListener(event: string, callback: () => void): void; + getDimensions(): { width: number, height: number }; + } + + module ToolBar { + export class Event { + static SIZE_CHANGED: string; + static CONTROL_REMOVED: string; + static CONTROL_ADDED: string; + static COLLAPSED_CHANGED: string; + static VISIBILITY_CHANGED: string; + } + } + + export interface ClientRect { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; + } + + export interface ContentSize { + height: number; + width: number; + } + + export class DockingPanel { + constructor(parentContainer: any, id: string, title: string, options?: any); + + closer: HTMLElement; + container: any; + content: any; + id: string; + scrollContainer: HTMLElement; + title: string; + titleTable: string; + + initialize(): void; + uninitialize(): void; + setVisible(show: boolean): void; + isVisible(): boolean; + getContentSize(): ContentSize; + resizeToContent(): void; + getContainerBoundingRect(): ClientRect; + setTitle(text: string, options: any): void; + createCloseButton(): HTMLElement; + createScrollContainer(options: { + heightAdjustment?: number; + left?: boolean; + marginTop?: number; + }): void; + initializeMoveHandlers(mover: HTMLElement): void; + initializeCloseHandler(close: HTMLElement): void; + + visibilityChanged(): void; + onStartMove(event: MouseEvent, startX: number, startY: number): void; + onEndMove(event: MouseEvent, endX: number, endY: number): void; + onMove(event: MouseEvent, currentX: number, currentY: number): void; + onTitleClick(event: Event): void; + onTitleDoubleClick(event: Event): void; + + addVisibilityListener(callback: (state: boolean) => void): void; + + addEventListener(target: Object, eventId: string, callback: (event: any) => void): void; + removeEventListener(target: Object, eventId: string, callback: (event: any) => void): boolean; + } + } + } +} diff --git a/types/forge-apis/tsconfig.json b/types/forge-apis/tsconfig.json new file mode 100644 index 0000000000..1b591ad13e --- /dev/null +++ b/types/forge-apis/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", + "forge-apis-tests.ts" + ] +} diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json new file mode 100644 index 0000000000..423e7ec10a --- /dev/null +++ b/types/forge-apis/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} From 54fb0ae75a9ca1b3980d9334e3d0bfbd47f747c3 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Mon, 14 Jan 2019 22:52:25 +0800 Subject: [PATCH 010/312] Delete package.json --- types/forge-apis/package.json | 38 ----------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 types/forge-apis/package.json diff --git a/types/forge-apis/package.json b/types/forge-apis/package.json deleted file mode 100644 index 7ab6a26459..0000000000 --- a/types/forge-apis/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "forge-api.typescript", - "version": "0.0.1", - "homepage": "https://github.com/cyrillef/forge-api.typescript", - "author": "Cyrille Fauvel", - "contributors": [ - "Cyrille Fauvel " - ], - "repository": { - "type": "git", - "url": "git+https://github.com/cyrillef/forge-api.typescript.git" - }, - "bugs": { - "url": "https://github.com/cyrillef/forge-api.typescript/issues" - }, - "keywords": [ - "typescript", - "forge", - "autodesk", - "api" - ], - "engines": { - "node": ">=8.0.0" - }, - "license": "MIT", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc" - }, - "dependencies": {}, - "devDependencies": { - "@types/three": "^0.93.15", - "typescript": "^3.2.1", - "typings": "^2.1.1" - }, - "optionalDependencies": {} -} From 1750132df28744a2d349fa3ad819ece587c3c32c Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Mon, 14 Jan 2019 23:03:22 +0800 Subject: [PATCH 011/312] Upgrade to TypeScript Version: 2.8 Upgrade to TypeScript Version: 2.8 --- types/forge-apis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index 8f984d633d..cbbd383d1b 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.8 // Copyright (c) Autodesk, Inc. All rights reserved // From 2dc140b2bdc72b252aa515e4d311a6c4e9cbcc93 Mon Sep 17 00:00:00 2001 From: Sunil Pai Date: Mon, 14 Jan 2019 21:25:15 +0000 Subject: [PATCH 012/312] react - rename useImperativeMethods -> useImperativeHandle --- types/react/index.d.ts | 8 ++++---- types/react/test/hooks.tsx | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 11d879b2ff..179f8bf73f 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -863,15 +863,15 @@ declare namespace React { function useEffect(effect: EffectCallback, inputs?: InputIdentityList): void; // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref /** - * `useImperativeMethods` customizes the instance value that is exposed to parent components when using + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using * `ref`. As always, imperative code using refs should be avoided in most cases. * - * `useImperativeMethods` should be used with `React.forwardRef`. + * `useImperativeHandle` should be used with `React.forwardRef`. * * @version experimental - * @see https://reactjs.org/docs/hooks-reference.html#useimperativemethods + * @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle */ - function useImperativeMethods(ref: Ref|undefined, init: () => R, inputs?: InputIdentityList): void; + function useImperativeHandle(ref: Ref|undefined, init: () => R, inputs?: InputIdentityList): void; // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. /** diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 5239d3b522..5cb0c1512c 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -21,7 +21,7 @@ export const FancyButton = React.forwardRef((props: FancyButtonProps, ref: React const buttonRef = React.useRef(null); const [count, setCount] = React.useState(0); - React.useImperativeMethods(ref, () => ({ + React.useImperativeHandle(ref, () => ({ fancyClick() { buttonRef.current!; // $ExpectType HTMLButtonElement }, @@ -91,7 +91,7 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { const didLayout = React.useRef(false); const id = React.useMemo(() => Math.random(), []); - React.useImperativeMethods(ref, () => ({ id }), [id]); + React.useImperativeHandle(ref, () => ({ id }), [id]); // $ExpectError React.useImperativeMethods(ref, () => ({}), [id]); From 6f7766f0cf4cec7132a361002809abff75bfdd0b Mon Sep 17 00:00:00 2001 From: Sunil Pai Date: Mon, 14 Jan 2019 21:42:52 +0000 Subject: [PATCH 013/312] update version number --- types/react/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 179f8bf73f..f2626e95b7 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React 16.7 +// Type definitions for React 16.8 // Project: http://facebook.github.io/react/ // Definitions by: Asana // AssureSign @@ -20,6 +20,7 @@ // Frank Li // Jessica Franco // Paul Sherman +// Sunil Pai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 From d0303873f12ad97ee398899dd4607d14a8c2b8d2 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 10:37:37 +0800 Subject: [PATCH 014/312] Update tslint.json --- types/forge-apis/tslint.json | 78 +----------------------------------- 1 file changed, 1 insertion(+), 77 deletions(-) diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json index 423e7ec10a..f93cf8562a 100644 --- a/types/forge-apis/tslint.json +++ b/types/forge-apis/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From ee0b5f2be32bd1c8817f0e777bc150f951f00b9f Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 14:40:51 +0800 Subject: [PATCH 015/312] Fixed linting errors Fixed linting errors --- types/forge-apis/forge-apis-tests.ts | 14 +- types/forge-apis/index.d.ts | 3 +- types/forge-apis/src/forge-apis.d.ts | 148 ++++++++-------- types/forge-apis/src/forge.d.ts | 22 +-- types/forge-apis/src/viewer.d.ts | 242 +++++++++++++-------------- types/forge-apis/tslint.json | 5 +- 6 files changed, 218 insertions(+), 216 deletions(-) diff --git a/types/forge-apis/forge-apis-tests.ts b/types/forge-apis/forge-apis-tests.ts index e25c781890..d7031facb9 100644 --- a/types/forge-apis/forge-apis-tests.ts +++ b/types/forge-apis/forge-apis-tests.ts @@ -1,13 +1,13 @@ -import {AuthClientTwoLegged, AuthClientThreeLegged, BucketsApi, HubsApi, FoldersApi, DerivativesApi} from 'forge-apis' +import { AuthClientTwoLegged, AuthClientThreeLegged, BucketsApi, HubsApi, FoldersApi, DerivativesApi } from 'forge-apis'; -var authClientTwoLegged: AuthClientTwoLegged = new AuthClientTwoLegged("","",[]); +const authClientTwoLegged: AuthClientTwoLegged = new AuthClientTwoLegged("", "", []); -var authClientThreeLegged: AuthClientThreeLegged = new AuthClientThreeLegged("","","",[]); +const authClientThreeLegged: AuthClientThreeLegged = new AuthClientThreeLegged("", "", "", []); -var bucketsApi: BucketsApi = new BucketsApi(); +const bucketsApi: BucketsApi = new BucketsApi(); -var hubsApi: HubsApi = new HubsApi(); +const hubsApi: HubsApi = new HubsApi(); -var foldersApi: FoldersApi = new FoldersApi(); +const foldersApi: FoldersApi = new FoldersApi(); -var derivativesApi: DerivativesApi = new DerivativesApi(); +const derivativesApi: DerivativesApi = new DerivativesApi(); diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index cbbd383d1b..77edab46f2 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Forge Node.js SDK +// sadsa // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -20,6 +20,5 @@ // UNINTERRUPTED OR ERROR FREE. // /// -/// /// /// diff --git a/types/forge-apis/src/forge-apis.d.ts b/types/forge-apis/src/forge-apis.d.ts index 2ae2d8dde6..cd13315914 100644 --- a/types/forge-apis/src/forge-apis.d.ts +++ b/types/forge-apis/src/forge-apis.d.ts @@ -15,95 +15,95 @@ // UNINTERRUPTED OR ERROR FREE. // declare module 'forge-apis' { - export class AuthClientTwoLegged { - constructor(clientId: string, clientSecret: string, scope: string[]); + class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); - authenticate(): Promise; - getCredentials(): Autodesk.Forge.AuthToken; - setCredentials(credentials: Autodesk.Forge.AuthToken): void; - isAuthorized(): boolean; - } + authenticate(): Promise; + getCredentials(): Autodesk.Forge.AuthToken; + setCredentials(credentials: Autodesk.Forge.AuthToken): void; + isAuthorized(): boolean; + } - export class AuthClientThreeLegged { - constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); - generateAuthUrl(): string; - getToken(code: string): Promise; - refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; - } + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; + } - export interface ApiResponse { - body: any; - headers: any; - statusCode: number; - } + interface ApiResponse { + body: any; + headers: any; + statusCode: number; + } - export interface ApiError { - statusCode: number; - statusMessage: string; - } + interface ApiError { + statusCode: number; + statusMessage: string; + } - export class BucketsApi { - constructor(); + class BucketsApi { + constructor(); - createBucket(postBuckets: Object, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBuckets(options: Object, credentials: Autodesk.Forge.AuthToken): Promise; - } + createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; + } - export class HubsApi { - constructor(); + class HubsApi { + constructor(); - getHub(hubId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubs(opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubProjects(hubId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - } + getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + } - export class FoldersApi { - constructor(); + class FoldersApi { + constructor(); - getFolderContents(projectId: string, folderId: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - } + getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + } - export interface JobPayload { - input: JobPayloadInput; - output: JobPayloadOutput; - } + interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; + } - export interface JobPayloadInput { - urn: string; - compressedUrn?: boolean; - rootFilename?: string; - } + interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; + } - export interface JobPayloadOutput { - formats: JobPayloadItem[]; - } + interface JobPayloadOutput { + formats: JobPayloadItem[]; + } - export interface JobPayloadItem { - type: string; - views?: string[]; - advanced?: { - applicationProtocol: string; - tolerance: number; - }, - format?: string; - exportColor?: boolean; - exportFileStructure?: string; - } + interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }; + format?: string; + exportColor?: boolean; + exportFileStructure?: string; + } - export class DerivativesApi { - constructor(); + class DerivativesApi { + constructor(); - deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; - getDerivativeManifest(urn: string, derivativeUrn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getFormats(opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getManifest(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getMetadata(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewMetadata(urn: string, guid: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewProperties(urn: string, guid: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - getThumbnail(urn: string, opts: Object, credentials: Autodesk.Forge.AuthToken): Promise; - translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; - } + deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; + } } diff --git a/types/forge-apis/src/forge.d.ts b/types/forge-apis/src/forge.d.ts index 2b126eac9e..a7c71f002b 100644 --- a/types/forge-apis/src/forge.d.ts +++ b/types/forge-apis/src/forge.d.ts @@ -14,35 +14,35 @@ // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // -declare module Autodesk { - export module Forge { - export interface Credentials { +declare namespace Autodesk { + namespace Forge { + interface Credentials { client_id: string; client_secret: string; grant_type: string; scope?: string; } - export interface AuthToken { + interface AuthToken { access_token: string; expires_in: number; token_type: string; refresh_token?: string; } - export module Dm { - export interface BucketResponse { + namespace Dm { + interface BucketResponse { bucketKey: string; bucketOwner: string; createdDate: number; - permissions: { + permissions: Array<{ access: string; authId: string; - }[]; + }>; policyKey: string; } - export interface ItemResponse { + interface ItemResponse { data: any[]; included: Item[]; jsonapi: { @@ -51,12 +51,12 @@ declare module Autodesk { links: any; } - export interface Item { + interface Item { attributes: { createTime: string; createUserId: string; displayName: string; - extension: Object; + extension: object; fileType: string; lastModifiedTime: string; lastModifiedUserId: string; diff --git a/types/forge-apis/src/viewer.d.ts b/types/forge-apis/src/viewer.d.ts index ca847ee2c1..0b28cc720f 100644 --- a/types/forge-apis/src/viewer.d.ts +++ b/types/forge-apis/src/viewer.d.ts @@ -16,47 +16,46 @@ // /// -declare module Autodesk { - export module Viewing { +declare namespace Autodesk { + namespace Viewing { // events - export var ESCAPE_EVENT: string; - export var PROGRESS_UPDATE_EVENT: string; - export var FULLSCREEN_MODE_EVENT: string; - export var NAVIGATION_MODE_CHANGED_EVENT: string; - export var VIEWER_STATE_RESTORED_EVENT: string; - export var VIEWER_RESIZE_EVENT: string; - export var VIEWER_UNINITIALIZED: string; - export var MODEL_ROOT_LOADED_EVENT: string; - export var GEOMETRY_LOADED_EVENT: string; - export var TOOLBAR_CREATED_EVENT: string; - export var OBJECT_TREE_CREATED_EVENT: string; - export var OBJECT_TREE_UNAVAILABLE_EVENT: string; - export var MODEL_UNLOADED_EVENT: string; - export var SELECTION_CHANGED_EVENT: string; - export var AGGREGATE_SELECTION_CHANGED_EVENT: string; - export var ISOLATE_EVENT: string; - export var HIDE_EVENT: string; - export var SHOW_EVENT: string; - export var HIGHLIGHT_EVENT: string; - export var CAMERA_CHANGE_EVENT: string; - export var EXPLODE_CHANGE_EVENT: string; - export var CUTPLANES_CHANGE_EVENT: string; - export var TOOL_CHANGE_EVENT: string; - export var TOOLBAR_CREATED_EVENT: string; - export var RENDER_OPTION_CHANGED_EVENT: string; - export var LAYER_VISIBILITY_CHANGED_EVENT: string; - export var RESET_EVENT: string; - export var ANIMATION_READY_EVENT: string; + let ESCAPE_EVENT: string; + let PROGRESS_UPDATE_EVENT: string; + let FULLSCREEN_MODE_EVENT: string; + let NAVIGATION_MODE_CHANGED_EVENT: string; + let VIEWER_STATE_RESTORED_EVENT: string; + let VIEWER_RESIZE_EVENT: string; + let VIEWER_UNINITIALIZED: string; + let MODEL_ROOT_LOADED_EVENT: string; + let GEOMETRY_LOADED_EVENT: string; + let TOOLBAR_CREATED_EVENT: string; + let OBJECT_TREE_CREATED_EVENT: string; + let OBJECT_TREE_UNAVAILABLE_EVENT: string; + let MODEL_UNLOADED_EVENT: string; + let SELECTION_CHANGED_EVENT: string; + let AGGREGATE_SELECTION_CHANGED_EVENT: string; + let ISOLATE_EVENT: string; + let HIDE_EVENT: string; + let SHOW_EVENT: string; + let HIGHLIGHT_EVENT: string; + let CAMERA_CHANGE_EVENT: string; + let EXPLODE_CHANGE_EVENT: string; + let CUTPLANES_CHANGE_EVENT: string; + let TOOL_CHANGE_EVENT: string; + let RENDER_OPTION_CHANGED_EVENT: string; + let LAYER_VISIBILITY_CHANGED_EVENT: string; + let RESET_EVENT: string; + let ANIMATION_READY_EVENT: string; - export enum SelectionMode { + enum SelectionMode { LEAF_OBJECT, FIRST_OBJECT, LAST_OBJECT } - export var theExtensionManager: ExtensionManager; + let theExtensionManager: ExtensionManager; - export interface InitializerOptions { + interface InitializerOptions { env?: string; language?: string; webGLHelpLink?: string; @@ -64,43 +63,44 @@ declare module Autodesk { refreshToken?(callback?: (accessToken: string, expires?: number) => void): void; } - export function Initializer(options: InitializerOptions, callback?: () => void): void; + function Initializer(options: InitializerOptions, callback?: () => void): void; - export class Document { - static load(documentId: string, successCallback: (doc: Document) => void, errorCallback: (errorCode: number, errorMsg: string, messages: any[]) => void, accessControlProperties?: any): void; - static getSubItemsWithProperties(item: Object, properties: Properties, recursive: boolean): Object[]; + class Document { + static load(documentId: string, successCallback: (doc: Document) => void, + errorCallback: (errorCode: number, errorMsg: string, messages: any[]) => void, accessControlProperties?: any): void; + static getSubItemsWithProperties(item: object, properties: Properties, recursive: boolean): object[]; acmSessionId: string; - getRootItem(): Object; - getViewablePath(item: Object): string; + getRootItem(): object; + getViewablePath(item: object): string; } - export class Extension { - viewer: Autodesk.Viewing.Private.GuiViewer3D; + class Extension { + viewer: Private.GuiViewer3D; options: any; - constructor(viewer: Autodesk.Viewing.Private.GuiViewer3D, options: any); + constructor(viewer: Private.GuiViewer3D, options: any); load(): boolean; unload(): boolean; } - export class ExtensionManager { + class ExtensionManager { registerExtension(extensionId: string, extension: any): boolean; unregisterExtension(extensionId: string): boolean; getExtension(extensionId: string): any; } - export class InstanceTree { + class InstanceTree { maxDepth: number; nodeAccess: InstanceTreeAccess; numHidden: number; numOff: number; objectCount: number; - enumNodeChildren(node: number|any, callback: (dbId: number) => void, recursive?: boolean): void; - enumNodeFragments(node: number|any, callback: (fragId: number) => void, recursive?: boolean): void; + enumNodeChildren(node: any, callback: (dbId: number) => void, recursive?: boolean): void; + enumNodeFragments(node: any, callback: (fragId: number) => void, recursive?: boolean): void; getChildCount(dbId: number): number; getNodeBox(dbId: number, nodeBox: Float32Array): void; getNodeParentId(dbId: number): number; @@ -109,7 +109,7 @@ declare module Autodesk { setFlagNode(dbId: number, flag: any, value: any): boolean; } - export class InstanceTreeAccess { + class InstanceTreeAccess { children: any; dbIdToIndex: any; nameSuffixes: any; @@ -122,14 +122,14 @@ declare module Autodesk { visibleIds: number; } - export interface InstanceTreeNode { + interface InstanceTreeNode { dbId: number; name: string; fragments: number[]; children: InstanceTreeNode[]; } - export class Model { + class Model { getBoundingBox(): THREE.Box3; getBulkProperties(dbIds: number[], propFilter?: string[], successCallback?: (r: any) => void, errorCallback?: (err: any) => void): void; getData(): any; @@ -138,7 +138,7 @@ declare module Autodesk { getProperties(dbId: number, successCallback?: (r: PropertyResult) => void, errorCallback?: (err: any) => void): void; getUnitScale(): number; getUnitString(): number; - //search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; + // search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; search(text: string, successCallback: (r: number[]) => void, errorCallback?: (err: any) => void, attributeNames?: string[]): void; clearThemingColors(): void; @@ -146,14 +146,14 @@ declare module Autodesk { visibilityManager: Private.VisibilityManager; } - export interface PropertyResult { + interface PropertyResult { dbId: number; externalId?: string; name?: string; properties: Property[]; } - export interface Property { + interface Property { displayCategory: string; displayName: string; displayValue: string; @@ -162,7 +162,7 @@ declare module Autodesk { units: string; } - export class Navigation { + class Navigation { getCamera(): any; getEyeVector(): THREE.Vector3; getFovMin(): number; @@ -179,27 +179,27 @@ declare module Autodesk { setCameraUpVector(up: THREE.Vector): void; } - export interface Properties { + interface Properties { type: string; role: string; } - export class ToolController { + class ToolController { activateTool(name: string): boolean; deactivateTool(name: string): boolean; registerTool(tool: any): boolean; deregisterTool(tool: any): boolean; getToolNames(): string[]; - getActiveToolName (): string; + getActiveToolName(): string; } - export interface ToolInterface { + interface ToolInterface { getCursor?(): string; getName(): string; getNames(): string[]; register(): void; deregister(): void; - activate(name: string, viewerApi?: Autodesk.Viewing.Private.GuiViewer3D): void; + activate(name: string, viewerApi?: Private.GuiViewer3D): void; deactivate(name: string): void; update(): boolean; handleSingleClick?(event: MouseEvent, button: number): boolean; @@ -217,22 +217,22 @@ declare module Autodesk { handleResize?(): void; } - export class UnifiedCamera { + class UnifiedCamera { } - export interface ContextMenuCallbackStatus { - hasHidden: boolean, - hasSelected: boolean, - hasVisible: boolean, - numSelected: number + interface ContextMenuCallbackStatus { + hasHidden: boolean; + hasSelected: boolean; + hasVisible: boolean; + numSelected: number; } - export interface ContextMenuItem { - target: () => void, - title: string + interface ContextMenuItem { + target: () => void; + title: string; } - export class Viewer3D { + class Viewer3D { id: number; clearSelection(): void; @@ -257,7 +257,7 @@ declare module Autodesk { search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; select(dbIds: number | number[]): void; setCutPlanes(planes: THREE.Vector4[]): void; - setSelectionMode(mode: Autodesk.Viewing.SelectionMode): void; + setSelectionMode(mode: SelectionMode): void; setThemingColor(dbId: number, color: THREE.Vector4, model?: any): void; setUp(config?: any): void; setViewCube(face: string): void; @@ -269,20 +269,19 @@ declare module Autodesk { worldToClient(point: THREE.Vector3): THREE.Vector3; } - export class ViewingUtilities { + class ViewingUtilities { getHitPoint(x: number, y: number): THREE.Vector3; } - export module Private { + namespace Private { + function getHtmlTemplate(url: string, callback: (error: string, content: string) => void): void; - export function getHtmlTemplate(url: string, callback: (error: string, content: string) => void): void; - - export class GuiViewer3D extends Viewer3D { - constructor(container: HTMLElement, config?: Object); + class GuiViewer3D extends Viewer3D { + constructor(container: HTMLElement, config?: object); canvas: HTMLCanvasElement; container: Element; - toolController: Viewing.ToolController; + toolController: ToolController; impl: Viewer3DImpl; model: Model; navigation: Navigation; @@ -290,18 +289,20 @@ declare module Autodesk { getCamera(): UnifiedCamera; getToolbar(create: boolean): UI.ToolBar; initialize(): any; - load(urn: string, sharedPropertyDbPath?: string, onSuccesfullCallback?: () => void, onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; - loadModel(urn: string, options?: any, onSuccesfullCallback?: () => void, onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; - start(path?: string, options?: Object): any; + load(urn: string, sharedPropertyDbPath?: string, onSuccesfullCallback?: () => void, + onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; + loadModel(urn: string, options?: any, onSuccesfullCallback?: () => void, + onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; + start(path?: string, options?: object): any; finish(): any; - setUsePivotAlways(value: boolean):any; + setUsePivotAlways(value: boolean): any; - setGroundShadow (param: boolean):void ; - setGroundReflection (param: boolean):void ; - setOptimizeNavigation (param: boolean):void ; - setQualityLevel (useSAO: boolean, useFXAA: boolean):void ; + setGroundShadow(param: boolean): void ; + setGroundReflection(param: boolean): void ; + setOptimizeNavigation(param: boolean): void ; + setQualityLevel(useSAO: boolean, useFXAA: boolean): void; - loadExtension(extensionId: string, options?: Object): boolean; + loadExtension(extensionId: string, options?: object): boolean; unloadExtension(extensionId: string): boolean; getExtension(extensionId: string): Extension; @@ -311,19 +312,18 @@ declare module Autodesk { addEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; removeEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; - } - export interface HitTestResult { + interface HitTestResult { dbId: number; face: THREE.Face3; fragId: number; intersectPoint: THREE.Vector3; - model: Autodesk.Viewing.Model; + model: Model; } - export class HudMessage { - static displayMessage(container: Element, messageSpec: { + namespace HudMessage { + function displayMessage(container: Element, messageSpec: { msgTitleKey: string, msgTitleDefault?: string, messageKey: string, @@ -332,10 +332,10 @@ declare module Autodesk { checkboxChecked?: boolean }, closeCallback?: (event: any) => void, buttonCallback?: (event: any) => void, checkboxCallback?: (event: any) => void): void; - static dismiss(): boolean; + function dismiss(): boolean; } - export class Viewer3DImpl { + class Viewer3DImpl { constructor(thecanvas: any, theapi: any); visibilityManager: VisibilityManager; @@ -352,28 +352,28 @@ declare module Autodesk { sceneUpdated(param: boolean): void; } - export class VisibilityManager { + class VisibilityManager { constructor(viewerImpl: any, model: any); getHiddenNodes(): any; getInstanceTree(): InstanceTree; getIsolatedNodes(): any; - hide(node: number | Object): void; + hide(node: number | object): void; isNodeVisible(dbId: number): boolean; - isolate(node: number | Object): void; + isolate(node: number | object): void; isolateMultiple(nodeList: any[]): void; isolateNone(): void; setAllVisibility(visible: boolean): void; - setVisibilityOnNode(node: number | Object, visible: boolean): void; - setNodeOff(node: number | Object, isOff: boolean): void; - show(node: number | Object): void; - toggleVisibility(node: number | Object): void; - updateNodeVisibilityTracking(node: number | Object, visible: boolean): void; + setVisibilityOnNode(node: number | object, visible: boolean): void; + setNodeOff(node: number | object, isOff: boolean): void; + show(node: number | object): void; + toggleVisibility(node: number | object): void; + updateNodeVisibilityTracking(node: number | object, visible: boolean): void; } } - export module UI { - export class Control { + namespace UI { + class Control { container: HTMLElement; getId(): string; @@ -385,23 +385,23 @@ declare module Autodesk { setVisible(visible: boolean): boolean; } - export class Button extends Control { + class Button extends Control { constructor(id: string, options?: any); setIcon(iconClass: string): void; - getState(): Autodesk.Viewing.UI.Button.State; - setState(state: Autodesk.Viewing.UI.Button.State): boolean; + getState(): Button.State; + setState(state: Button.State): boolean; onClick(event: MouseEvent): void; onMouseOver(event: MouseEvent): void; onMouseOut(event: MouseEvent): void; } // NOTE: TypeScript doesn't support enum inside class - module Button { - export enum State { ACTIVE, INACTIVE, DISABLED } + namespace Button { + enum State { ACTIVE, INACTIVE, DISABLED } } - export class ControlGroup extends Control { + class ControlGroup extends Control { constructor(id: string, options?: any); addClass(name: string): void; @@ -411,22 +411,22 @@ declare module Autodesk { getNumberOfControls(): number; } - export class ToolBar extends ControlGroup { + class ToolBar extends ControlGroup { addEventListener(event: string, callback: () => void): void; getDimensions(): { width: number, height: number }; } - module ToolBar { - export class Event { - static SIZE_CHANGED: string; - static CONTROL_REMOVED: string; - static CONTROL_ADDED: string; - static COLLAPSED_CHANGED: string; - static VISIBILITY_CHANGED: string; + namespace ToolBar { + interface Event { + SIZE_CHANGED: string; + CONTROL_REMOVED: string; + CONTROL_ADDED: string; + COLLAPSED_CHANGED: string; + VISIBILITY_CHANGED: string; } } - export interface ClientRect { + interface ClientRect { bottom: number; height: number; left: number; @@ -435,12 +435,12 @@ declare module Autodesk { width: number; } - export interface ContentSize { + interface ContentSize { height: number; width: number; } - export class DockingPanel { + class DockingPanel { constructor(parentContainer: any, id: string, title: string, options?: any); closer: HTMLElement; @@ -477,8 +477,8 @@ declare module Autodesk { addVisibilityListener(callback: (state: boolean) => void): void; - addEventListener(target: Object, eventId: string, callback: (event: any) => void): void; - removeEventListener(target: Object, eventId: string, callback: (event: any) => void): boolean; + addEventListener(target: object, eventId: string, callback: (event: any) => void): void; + removeEventListener(target: object, eventId: string, callback: (event: any) => void): boolean; } } } diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json index f93cf8562a..891d897c91 100644 --- a/types/forge-apis/tslint.json +++ b/types/forge-apis/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false + } } From aeef227053c9a050a179b108473187f8fc35f587 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 14:41:17 +0800 Subject: [PATCH 016/312] Delete viewer-extensions.d.ts --- types/forge-apis/src/viewer-extensions.d.ts | 66 --------------------- 1 file changed, 66 deletions(-) delete mode 100644 types/forge-apis/src/viewer-extensions.d.ts diff --git a/types/forge-apis/src/viewer-extensions.d.ts b/types/forge-apis/src/viewer-extensions.d.ts deleted file mode 100644 index 4b5bf53a1f..0000000000 --- a/types/forge-apis/src/viewer-extensions.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (c) Autodesk, Inc. All rights reserved -// -// Permission to use, copy, modify, and distribute this software in -// object code form for any purpose and without fee is hereby granted, -// provided that the above copyright notice appears in all copies and -// that both that copyright notice and the limited warranty and -// restricted rights notice below appear in all supporting -// documentation. -// -// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. -// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF -// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. -// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE -// UNINTERRUPTED OR ERROR FREE. -// -/// - -declare module Autodesk { - export module Viewing { - export module Extensions { - export module Markups { - export module Core { - export class MarkupsCore extends Autodesk.Viewing.Extension { - duringEditMode: boolean; - duringViewMode: boolean; - - enterEditMode(): boolean; - leaveEditMode(): boolean; - changeEditMode(mode: EditMode): void; - hide(): boolean; - show(): boolean; - toggle(): boolean; - clear(): void; - generateData(): string; - generatePoints3d(): any; - allowNavigation(allow: boolean): void; - disableMarkupInteractions(disable: boolean): void; - } - - export class EditMode { - constructor(extension: Autodesk.Viewing.Extension); - } - - export class EditModeArrow extends EditMode { - } - - export class EditModeCircle extends EditMode { - } - - export class EditModeCloud extends EditMode { - } - - export class EditModeFreehand extends EditMode { - } - - export class EditModeRectangle extends EditMode { - } - - export class EditModeText extends EditMode { - } - } - } - } - } -} \ No newline at end of file From a6d58f91ffbb027af5fa5af1ef43a7ff0101140a Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 14:49:44 +0800 Subject: [PATCH 017/312] fixed definition header --- types/forge-apis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index 77edab46f2..68678aa5b8 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,4 +1,4 @@ -// sadsa +// Type definitions for Forge Node.js SDK // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From c736f43326c7dfb9b6c5bc228a1ffb39db7e1104 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 15:49:50 +0800 Subject: [PATCH 018/312] moved module definitions to index.d.ts --- types/forge-apis/index.d.ts | 95 ++++++++++++++++++++++++++++++++++++- 1 file changed, 93 insertions(+), 2 deletions(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index 68678aa5b8..bbf772035f 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Forge Node.js SDK +// Type definitions for Forge-apis // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,4 +21,95 @@ // /// /// -/// + +export class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); + + authenticate(): Promise; + getCredentials(): Autodesk.Forge.AuthToken; + setCredentials(credentials: Autodesk.Forge.AuthToken): void; + isAuthorized(): boolean; +} + +export class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; +} + +export interface ApiResponse { + body: any; + headers: any; + statusCode: number; +} + +export interface ApiError { + statusCode: number; + statusMessage: string; +} + +export class BucketsApi { + constructor(); + + createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export class HubsApi { + constructor(); + + getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export class FoldersApi { + constructor(); + + getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; +} + +export interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; +} + +export interface JobPayloadOutput { + formats: JobPayloadItem[]; +} + +export interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }; + format?: string; + exportColor?: boolean; + exportFileStructure?: string; +} + +export class DerivativesApi { + constructor(); + + deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; +} From 80fcf2ee57dff01481ebe615e4c70e6cb1fc12e4 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 15:50:06 +0800 Subject: [PATCH 019/312] Delete forge-apis.d.ts --- types/forge-apis/src/forge-apis.d.ts | 109 --------------------------- 1 file changed, 109 deletions(-) delete mode 100644 types/forge-apis/src/forge-apis.d.ts diff --git a/types/forge-apis/src/forge-apis.d.ts b/types/forge-apis/src/forge-apis.d.ts deleted file mode 100644 index cd13315914..0000000000 --- a/types/forge-apis/src/forge-apis.d.ts +++ /dev/null @@ -1,109 +0,0 @@ -// -// Copyright (c) Autodesk, Inc. All rights reserved -// -// Permission to use, copy, modify, and distribute this software in -// object code form for any purpose and without fee is hereby granted, -// provided that the above copyright notice appears in all copies and -// that both that copyright notice and the limited warranty and -// restricted rights notice below appear in all supporting -// documentation. -// -// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. -// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF -// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. -// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE -// UNINTERRUPTED OR ERROR FREE. -// -declare module 'forge-apis' { - class AuthClientTwoLegged { - constructor(clientId: string, clientSecret: string, scope: string[]); - - authenticate(): Promise; - getCredentials(): Autodesk.Forge.AuthToken; - setCredentials(credentials: Autodesk.Forge.AuthToken): void; - isAuthorized(): boolean; - } - - class AuthClientThreeLegged { - constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); - - generateAuthUrl(): string; - getToken(code: string): Promise; - refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; - } - - interface ApiResponse { - body: any; - headers: any; - statusCode: number; - } - - interface ApiError { - statusCode: number; - statusMessage: string; - } - - class BucketsApi { - constructor(); - - createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; - } - - class HubsApi { - constructor(); - - getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - } - - class FoldersApi { - constructor(); - - getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - } - - interface JobPayload { - input: JobPayloadInput; - output: JobPayloadOutput; - } - - interface JobPayloadInput { - urn: string; - compressedUrn?: boolean; - rootFilename?: string; - } - - interface JobPayloadOutput { - formats: JobPayloadItem[]; - } - - interface JobPayloadItem { - type: string; - views?: string[]; - advanced?: { - applicationProtocol: string; - tolerance: number; - }; - format?: string; - exportColor?: boolean; - exportFileStructure?: string; - } - - class DerivativesApi { - constructor(); - - deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; - getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; - } -} From 77cf402c56504f954a18f045a61ae8d3248bd25b Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 15:55:24 +0800 Subject: [PATCH 020/312] Add files via upload --- types/forge-apis/index.d.ts | 95 +------------------------------------ 1 file changed, 2 insertions(+), 93 deletions(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index bbf772035f..ba121db0ad 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Forge-apis +// Type definitions for Forge-apis 0.4.4 // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,95 +21,4 @@ // /// /// - -export class AuthClientTwoLegged { - constructor(clientId: string, clientSecret: string, scope: string[]); - - authenticate(): Promise; - getCredentials(): Autodesk.Forge.AuthToken; - setCredentials(credentials: Autodesk.Forge.AuthToken): void; - isAuthorized(): boolean; -} - -export class AuthClientThreeLegged { - constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); - - generateAuthUrl(): string; - getToken(code: string): Promise; - refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; -} - -export interface ApiResponse { - body: any; - headers: any; - statusCode: number; -} - -export interface ApiError { - statusCode: number; - statusMessage: string; -} - -export class BucketsApi { - constructor(); - - createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; -} - -export class HubsApi { - constructor(); - - getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; -} - -export class FoldersApi { - constructor(); - - getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; -} - -export interface JobPayload { - input: JobPayloadInput; - output: JobPayloadOutput; -} - -export interface JobPayloadInput { - urn: string; - compressedUrn?: boolean; - rootFilename?: string; -} - -export interface JobPayloadOutput { - formats: JobPayloadItem[]; -} - -export interface JobPayloadItem { - type: string; - views?: string[]; - advanced?: { - applicationProtocol: string; - tolerance: number; - }; - format?: string; - exportColor?: boolean; - exportFileStructure?: string; -} - -export class DerivativesApi { - constructor(); - - deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; - getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; -} +/// From 4f090983132d22e45b6d4e55bbad077d7427a844 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 16:06:55 +0800 Subject: [PATCH 021/312] Add files via upload --- types/forge-apis/index.d.ts | 93 ++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index ba121db0ad..d3abc751c9 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -21,4 +21,95 @@ // /// /// -/// + +export class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); + + authenticate(): Promise; + getCredentials(): Autodesk.Forge.AuthToken; + setCredentials(credentials: Autodesk.Forge.AuthToken): void; + isAuthorized(): boolean; +} + +export class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; +} + +export interface ApiResponse { + body: any; + headers: any; + statusCode: number; +} + +export interface ApiError { + statusCode: number; + statusMessage: string; +} + +export class BucketsApi { + constructor(); + + createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; + getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export class HubsApi { + constructor(); + + getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export class FoldersApi { + constructor(); + + getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; +} + +export interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; +} + +export interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; +} + +export interface JobPayloadOutput { + formats: JobPayloadItem[]; +} + +export interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }; + format?: string; + exportColor?: boolean; + exportFileStructure?: string; +} + +export class DerivativesApi { + constructor(); + + deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; +} From 9f1fe3db77516fb1fb608753e2f3924dd605b362 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 16:11:44 +0800 Subject: [PATCH 022/312] Fixed version number --- types/forge-apis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index d3abc751c9..83f57310c8 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Forge-apis 0.4.4 +// Type definitions for Forge-apis 0.4 // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client // Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 1eaceb3359c5eca1359605ea6c130a64573c770d Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 16:21:22 +0800 Subject: [PATCH 023/312] fixed author info --- types/forge-apis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index 83f57310c8..aa8ea565cf 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Forge-apis 0.4 // Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client -// Definitions by: Autodesk Forge Partner Development +// Definitions by: Autodesk Forge Partner Development // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 From f8b663aa87a700e3fb1679c88cb8cb8e6fe41e72 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Tue, 15 Jan 2019 16:32:12 +0800 Subject: [PATCH 024/312] Use standard tslint.json --- types/forge-apis/tslint.json | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json index 891d897c91..f93cf8562a 100644 --- a/types/forge-apis/tslint.json +++ b/types/forge-apis/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-single-declare-module": false - } + "extends": "dtslint/dt.json" } From 547fd3a4724900834f2d9da46f0145e2a509adb7 Mon Sep 17 00:00:00 2001 From: Scott Humphries Date: Tue, 15 Jan 2019 18:35:48 -0600 Subject: [PATCH 025/312] frisby uses jest typings --- types/frisby/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/frisby/index.d.ts b/types/frisby/index.d.ts index 1bcd6fdabb..85151daa68 100644 --- a/types/frisby/index.d.ts +++ b/types/frisby/index.d.ts @@ -5,7 +5,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -/// +/// // #region Imports export import nodeFetch = require('node-fetch'); // Import all definitions from node-fetch. From 1bbc85aaf175706e6b02ab4e6a323dd08d720eb1 Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Wed, 16 Jan 2019 10:44:43 +0800 Subject: [PATCH 026/312] moving globals from forge.d.ts to top level --- types/forge-apis/index.d.ts | 125 +++++++++++++++++++++++++++++------- 1 file changed, 102 insertions(+), 23 deletions(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index aa8ea565cf..c7fcdc3c5a 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -20,14 +20,13 @@ // UNINTERRUPTED OR ERROR FREE. // /// -/// export class AuthClientTwoLegged { constructor(clientId: string, clientSecret: string, scope: string[]); - authenticate(): Promise; - getCredentials(): Autodesk.Forge.AuthToken; - setCredentials(credentials: Autodesk.Forge.AuthToken): void; + authenticate(): Promise; + getCredentials(): AuthToken; + setCredentials(credentials: AuthToken): void; isAuthorized(): boolean; } @@ -35,8 +34,8 @@ export class AuthClientThreeLegged { constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); generateAuthUrl(): string; - getToken(code: string): Promise; - refreshToken(credentials: Autodesk.Forge.AuthToken): Promise; + getToken(code: string): Promise; + refreshToken(credentials: AuthToken): Promise; } export interface ApiResponse { @@ -53,24 +52,24 @@ export interface ApiError { export class BucketsApi { constructor(); - createBucket(postBuckets: object, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - deleteBucket(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBucketDetails(bucketKey: string, credentials: Autodesk.Forge.AuthToken): Promise; - getBuckets(options: object, credentials: Autodesk.Forge.AuthToken): Promise; + createBucket(postBuckets: object, opts: object, credentials: AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: AuthToken): Promise; + getBuckets(options: object, credentials: AuthToken): Promise; } export class HubsApi { constructor(); - getHub(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubs(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getHubProjects(hubId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getHub(hubId: string, opts: object, credentials: AuthToken): Promise; + getHubs(opts: object, credentials: AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: AuthToken): Promise; } export class FoldersApi { constructor(); - getFolderContents(projectId: string, folderId: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; + getFolderContents(projectId: string, folderId: string, opts: object, credentials: AuthToken): Promise; } export interface JobPayload { @@ -103,13 +102,93 @@ export interface JobPayloadItem { export class DerivativesApi { constructor(); - deleteManifest(urn: string, credentials: Autodesk.Forge.AuthToken): Promise; - getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getFormats(opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getManifest(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getMetadata(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewMetadata(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getModelviewProperties(urn: string, guid: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - getThumbnail(urn: string, opts: object, credentials: Autodesk.Forge.AuthToken): Promise; - translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: Autodesk.Forge.AuthToken): Promise; + deleteManifest(urn: string, credentials: AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: AuthToken): Promise; + getFormats(opts: object, credentials: AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: AuthToken): Promise; +} + +export interface Credentials { + client_id: string; + client_secret: string; + grant_type: string; + scope?: string; +} + +export interface AuthToken { + access_token: string; + expires_in: number; + token_type: string; + refresh_token?: string; +} + +export namespace Dm { + interface BucketResponse { + bucketKey: string; + bucketOwner: string; + createdDate: number; + permissions: Array<{ + access: string; + authId: string; + }>; + policyKey: string; + } + + interface ItemResponse { + data: any[]; + included: Item[]; + jsonapi: { + version: string; + }; + links: any; + } + + interface Item { + attributes: { + createTime: string; + createUserId: string; + displayName: string; + extension: object; + fileType: string; + lastModifiedTime: string; + lastModifiedUserId: string; + mimeType: string; + name: string; + storageSize: number; + versionNumber: number; + }; + id: string; + links: { + self: { + href: string; + }; + }; + relationships: { + derivatives: { + data: { + id: string; + }, + meta: { + link: { + href: string; + } + } + }, + item: any; + refs: any; + storage: { + data: { + id: string; + type: string; + } + }; + thumbnail: any; + }; + type: string; + } } From 9b0dc384dca43d529a234992397be6800d55dbbb Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Wed, 16 Jan 2019 10:45:01 +0800 Subject: [PATCH 027/312] Delete forge.d.ts --- types/forge-apis/src/forge.d.ts | 99 --------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 types/forge-apis/src/forge.d.ts diff --git a/types/forge-apis/src/forge.d.ts b/types/forge-apis/src/forge.d.ts deleted file mode 100644 index a7c71f002b..0000000000 --- a/types/forge-apis/src/forge.d.ts +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (c) Autodesk, Inc. All rights reserved -// -// Permission to use, copy, modify, and distribute this software in -// object code form for any purpose and without fee is hereby granted, -// provided that the above copyright notice appears in all copies and -// that both that copyright notice and the limited warranty and -// restricted rights notice below appear in all supporting -// documentation. -// -// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. -// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF -// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. -// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE -// UNINTERRUPTED OR ERROR FREE. -// -declare namespace Autodesk { - namespace Forge { - interface Credentials { - client_id: string; - client_secret: string; - grant_type: string; - scope?: string; - } - - interface AuthToken { - access_token: string; - expires_in: number; - token_type: string; - refresh_token?: string; - } - - namespace Dm { - interface BucketResponse { - bucketKey: string; - bucketOwner: string; - createdDate: number; - permissions: Array<{ - access: string; - authId: string; - }>; - policyKey: string; - } - - interface ItemResponse { - data: any[]; - included: Item[]; - jsonapi: { - version: string; - }; - links: any; - } - - interface Item { - attributes: { - createTime: string; - createUserId: string; - displayName: string; - extension: object; - fileType: string; - lastModifiedTime: string; - lastModifiedUserId: string; - mimeType: string; - name: string; - storageSize: number; - versionNumber: number; - }; - id: string; - links: { - self: { - href: string; - }; - }; - relationships: { - derivatives: { - data: { - id: string; - }, - meta: { - link: { - href: string; - } - } - }, - item: any; - refs: any; - storage: { - data: { - id: string; - type: string; - } - }; - thumbnail: any; - }; - type: string; - } - } - } -} From 0e9a7e2a6913f0496e617af710ac7047ae0c5c12 Mon Sep 17 00:00:00 2001 From: Erik Zivkovic Date: Tue, 15 Jan 2019 16:24:15 +0100 Subject: [PATCH 028/312] react-bootstrap: add missing bsClass, bsSize declarations I tried to find as many as possible of the declarations of bsClass, and bsSize that were missing. I used the following sources: * The documentation for pre-v1.0.0 react-bootstrap at https://react-bootstrap.github.io * Double checked using the source code for pre-v1.0.0 at https://github.com/react-bootstrap/react-bootstrap --- types/react-bootstrap/README.md | 13 +++++++++++++ types/react-bootstrap/index.d.ts | 1 + types/react-bootstrap/lib/Alert.d.ts | 1 + types/react-bootstrap/lib/ButtonGroup.d.ts | 1 + types/react-bootstrap/lib/ButtonToolbar.d.ts | 1 + types/react-bootstrap/lib/Clearfix.d.ts | 1 + types/react-bootstrap/lib/FormControlFeedback.d.ts | 4 +++- types/react-bootstrap/lib/InputGroupAddon.d.ts | 4 +++- types/react-bootstrap/lib/InputGroupButton.d.ts | 4 +++- types/react-bootstrap/lib/Modal.d.ts | 1 + types/react-bootstrap/lib/ModalDialog.d.ts | 3 +++ types/react-bootstrap/lib/ModalFooter.d.ts | 1 + types/react-bootstrap/lib/ModalTitle.d.ts | 1 + types/react-bootstrap/lib/Nav.d.ts | 1 + types/react-bootstrap/lib/PageHeader.d.ts | 4 +++- types/react-bootstrap/lib/Pager.d.ts | 1 + types/react-bootstrap/lib/Popover.d.ts | 1 + types/react-bootstrap/lib/ProgressBar.d.ts | 1 + types/react-bootstrap/lib/TabContent.d.ts | 1 + types/react-bootstrap/lib/Tooltip.d.ts | 1 + types/react-bootstrap/lib/Well.d.ts | 1 + 21 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 types/react-bootstrap/README.md diff --git a/types/react-bootstrap/README.md b/types/react-bootstrap/README.md new file mode 100644 index 0000000000..114130171d --- /dev/null +++ b/types/react-bootstrap/README.md @@ -0,0 +1,13 @@ +# react-bootstrap + +## Intended compatibilty +This library is intended for releases of react-bootstrap prior to `v1.0.0`, e.g. `v0.32.4`. + +The reason is that react-bootstrap `v1.0.0` targets Bootstrap v4, and includes its own +typings. react-bootstrap prior to `v1.0.0` targets Bootstrap v3 and does not include any +typings. + +It does not make sense for everyone to upgrade to Bootstrap v3, therefore these typings +are useful for everyone that wants to stay on Bootstrap v3 and react-bootstrap prior to `v1.0.0`. + +The typings for `v1.0.0` were merged in [this pull request](https://github.com/react-bootstrap/react-bootstrap/commit/2079b2292afb835d036fcceef47e8938c4a8d86a). diff --git a/types/react-bootstrap/index.d.ts b/types/react-bootstrap/index.d.ts index 83f5f8db61..c2de3d58b3 100644 --- a/types/react-bootstrap/index.d.ts +++ b/types/react-bootstrap/index.d.ts @@ -14,6 +14,7 @@ // Johann Rakotoharisoa // Andrew Makarov // Duong Tran +// Erik Zivkovic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-bootstrap/lib/Alert.d.ts b/types/react-bootstrap/lib/Alert.d.ts index 913619101f..eb6888d956 100644 --- a/types/react-bootstrap/lib/Alert.d.ts +++ b/types/react-bootstrap/lib/Alert.d.ts @@ -5,6 +5,7 @@ declare namespace Alert { export interface AlertProps extends React.HTMLProps { bsSize?: Sizes; bsStyle?: string; + bsClass?: string; closeLabel?: string; /** @deprecated since v0.29.0 */dismissAfter?: number; // TODO: Add more specific type diff --git a/types/react-bootstrap/lib/ButtonGroup.d.ts b/types/react-bootstrap/lib/ButtonGroup.d.ts index 681be17aef..3008e616c4 100644 --- a/types/react-bootstrap/lib/ButtonGroup.d.ts +++ b/types/react-bootstrap/lib/ButtonGroup.d.ts @@ -6,6 +6,7 @@ declare namespace ButtonGroup { block?: boolean; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; justified?: boolean; vertical?: boolean; } diff --git a/types/react-bootstrap/lib/ButtonToolbar.d.ts b/types/react-bootstrap/lib/ButtonToolbar.d.ts index 554f9d5583..d2a54d5b89 100644 --- a/types/react-bootstrap/lib/ButtonToolbar.d.ts +++ b/types/react-bootstrap/lib/ButtonToolbar.d.ts @@ -6,6 +6,7 @@ declare namespace ButtonToolbar { block?: boolean; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; justified?: boolean; vertical?: boolean; } diff --git a/types/react-bootstrap/lib/Clearfix.d.ts b/types/react-bootstrap/lib/Clearfix.d.ts index c248dde7c9..76303b3aff 100644 --- a/types/react-bootstrap/lib/Clearfix.d.ts +++ b/types/react-bootstrap/lib/Clearfix.d.ts @@ -7,6 +7,7 @@ declare namespace Clearfix { visibleSmBlock?: boolean; visibleMdBlock?: boolean; visibleLgBlock?: boolean; + bsClass?: string; } } declare class Clearfix extends React.Component { } diff --git a/types/react-bootstrap/lib/FormControlFeedback.d.ts b/types/react-bootstrap/lib/FormControlFeedback.d.ts index a81939becc..cdfc3aa4f6 100644 --- a/types/react-bootstrap/lib/FormControlFeedback.d.ts +++ b/types/react-bootstrap/lib/FormControlFeedback.d.ts @@ -1,7 +1,9 @@ import * as React from 'react'; declare namespace FormControlFeedback { - export type FormControlFeedbackProps = React.HTMLProps; + export interface FormControlFeedbackProps extends React.HTMLProps { + bsClass?: string; + } } declare class FormControlFeedback extends React.Component { } export = FormControlFeedback; diff --git a/types/react-bootstrap/lib/InputGroupAddon.d.ts b/types/react-bootstrap/lib/InputGroupAddon.d.ts index 720fecc704..40194d5b5d 100644 --- a/types/react-bootstrap/lib/InputGroupAddon.d.ts +++ b/types/react-bootstrap/lib/InputGroupAddon.d.ts @@ -1,7 +1,9 @@ import * as React from 'react'; declare namespace InputGroupAddon { - type InputGroupAddonProps = React.HTMLProps; + interface InputGroupAddonProps extends React.HTMLProps { + bsClass?: string; + } } declare class InputGroupAddon extends React.Component { } export = InputGroupAddon; diff --git a/types/react-bootstrap/lib/InputGroupButton.d.ts b/types/react-bootstrap/lib/InputGroupButton.d.ts index b050c9a2ec..a62ffc9d47 100644 --- a/types/react-bootstrap/lib/InputGroupButton.d.ts +++ b/types/react-bootstrap/lib/InputGroupButton.d.ts @@ -1,7 +1,9 @@ import * as React from 'react'; declare namespace InputGroupButton { - export type InputGroupButtonProps = React.HTMLProps; + export interface InputGroupButtonProps extends React.HTMLProps { + bsClass?: string; + } } declare class InputGroupButton extends React.Component { } export = InputGroupButton; diff --git a/types/react-bootstrap/lib/Modal.d.ts b/types/react-bootstrap/lib/Modal.d.ts index 9b5ada2cdc..80ffdf72f1 100644 --- a/types/react-bootstrap/lib/Modal.d.ts +++ b/types/react-bootstrap/lib/Modal.d.ts @@ -19,6 +19,7 @@ declare namespace Modal { backdropStyle?: any; backdropTransitionTimeout?: number; bsSize?: Sizes; + bsClass?: string; container?: any; // TODO: Add more specific type containerClassName?: string; dialogClassName?: string; diff --git a/types/react-bootstrap/lib/ModalDialog.d.ts b/types/react-bootstrap/lib/ModalDialog.d.ts index 4fb2568ab6..b5493998b9 100644 --- a/types/react-bootstrap/lib/ModalDialog.d.ts +++ b/types/react-bootstrap/lib/ModalDialog.d.ts @@ -1,4 +1,5 @@ import * as React from 'react'; +import { Sizes } from 'react-bootstrap'; declare namespace ModalDialog { export interface ModalDialogProps extends React.HTMLProps { @@ -10,6 +11,8 @@ declare namespace ModalDialog { onExit?: Function; onExited?: Function; onExiting?: Function; + bsSize?: Sizes; + bsClass?: string; } } declare class ModalDialog extends React.Component { } diff --git a/types/react-bootstrap/lib/ModalFooter.d.ts b/types/react-bootstrap/lib/ModalFooter.d.ts index e70b15e688..2f9f902a85 100644 --- a/types/react-bootstrap/lib/ModalFooter.d.ts +++ b/types/react-bootstrap/lib/ModalFooter.d.ts @@ -3,6 +3,7 @@ import * as React from 'react'; declare namespace ModalFooter { export interface ModalFooterProps extends React.HTMLProps { componentClass?: React.ReactType; + bsClass?: string; } } declare class ModalFooter extends React.Component { } diff --git a/types/react-bootstrap/lib/ModalTitle.d.ts b/types/react-bootstrap/lib/ModalTitle.d.ts index b1fd0b386e..a98e7fe3d3 100644 --- a/types/react-bootstrap/lib/ModalTitle.d.ts +++ b/types/react-bootstrap/lib/ModalTitle.d.ts @@ -3,6 +3,7 @@ import * as React from 'react'; declare namespace ModalTitle { export interface ModalTitleProps extends React.HTMLProps { componentClass?: React.ReactType; + bsClass?: string; } } declare class ModalTitle extends React.Component { } diff --git a/types/react-bootstrap/lib/Nav.d.ts b/types/react-bootstrap/lib/Nav.d.ts index 19afb12a7e..2e190662dc 100644 --- a/types/react-bootstrap/lib/Nav.d.ts +++ b/types/react-bootstrap/lib/Nav.d.ts @@ -8,6 +8,7 @@ declare namespace Nav { activeKey?: any; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; collapsible?: boolean; eventKey?: any; expanded?: boolean; diff --git a/types/react-bootstrap/lib/PageHeader.d.ts b/types/react-bootstrap/lib/PageHeader.d.ts index 2212463789..cbc25c3483 100644 --- a/types/react-bootstrap/lib/PageHeader.d.ts +++ b/types/react-bootstrap/lib/PageHeader.d.ts @@ -1,7 +1,9 @@ import * as React from 'react'; declare namespace PageHeader { - export type PageHeaderProps = React.HTMLProps; + export interface PageHeaderProps extends React.HTMLProps { + bsClass?: string; + } } declare class PageHeader extends React.Component { } export = PageHeader; diff --git a/types/react-bootstrap/lib/Pager.d.ts b/types/react-bootstrap/lib/Pager.d.ts index 076d30a0af..432d1d3ec4 100644 --- a/types/react-bootstrap/lib/Pager.d.ts +++ b/types/react-bootstrap/lib/Pager.d.ts @@ -5,6 +5,7 @@ import PagerItem = require('./PagerItem'); declare namespace Pager { export interface PagerProps extends React.HTMLProps { onSelect?: SelectCallback; + bsClass?: string; } } declare class Pager extends React.Component { diff --git a/types/react-bootstrap/lib/Popover.d.ts b/types/react-bootstrap/lib/Popover.d.ts index 95abc38854..b018b585d7 100644 --- a/types/react-bootstrap/lib/Popover.d.ts +++ b/types/react-bootstrap/lib/Popover.d.ts @@ -8,6 +8,7 @@ declare namespace Popover { arrowOffsetTop?: number | string; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; placement?: string; positionLeft?: number | string; // String support added since v0.30.0 positionTop?: number | string; // String support added since v0.30.0 diff --git a/types/react-bootstrap/lib/ProgressBar.d.ts b/types/react-bootstrap/lib/ProgressBar.d.ts index 8fc408ac65..add9b48529 100644 --- a/types/react-bootstrap/lib/ProgressBar.d.ts +++ b/types/react-bootstrap/lib/ProgressBar.d.ts @@ -7,6 +7,7 @@ declare namespace ProgressBar { active?: boolean; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; interpolatedClass?: any; // TODO: Add more specific type max?: number; min?: number; diff --git a/types/react-bootstrap/lib/TabContent.d.ts b/types/react-bootstrap/lib/TabContent.d.ts index 133727263c..61acf34c2e 100644 --- a/types/react-bootstrap/lib/TabContent.d.ts +++ b/types/react-bootstrap/lib/TabContent.d.ts @@ -6,6 +6,7 @@ declare namespace TabContent { animation?: boolean | React.ReactType; mountOnEnter?: boolean; unmountOnExit?: boolean; + bsClass?: string; } } declare class TabContent extends React.Component { } diff --git a/types/react-bootstrap/lib/Tooltip.d.ts b/types/react-bootstrap/lib/Tooltip.d.ts index 8363747293..c08e1a2f70 100644 --- a/types/react-bootstrap/lib/Tooltip.d.ts +++ b/types/react-bootstrap/lib/Tooltip.d.ts @@ -8,6 +8,7 @@ declare namespace Tooltip { arrowOffsetTop?: number | string; bsSize?: Sizes; bsStyle?: string; + bsClass?: string; placement?: string; positionLeft?: number; positionTop?: number; diff --git a/types/react-bootstrap/lib/Well.d.ts b/types/react-bootstrap/lib/Well.d.ts index 07656cc71b..026b66794d 100644 --- a/types/react-bootstrap/lib/Well.d.ts +++ b/types/react-bootstrap/lib/Well.d.ts @@ -5,6 +5,7 @@ declare namespace Well { export interface WellProps extends React.HTMLProps { bsSize?: Sizes; bsStyle?: string; + bsClass?: string; } } declare class Well extends React.Component { } From e896537a9c5697f7f6e7da7a7673d2524f1f8c73 Mon Sep 17 00:00:00 2001 From: Aleksandar Manukov <34056917+aleksandar-manukov@users.noreply.github.com> Date: Wed, 16 Jan 2019 22:12:26 +0200 Subject: [PATCH 029/312] Add tests for bootstrap-colorpicker-v2 --- .../bootstrap-colorpicker-v2-tests.ts | 77 +++++++++++++++++++ .../index.d.ts | 59 +++++++------- .../tsconfig.json | 2 +- .../tslint.json | 0 .../bootstrap-colorpicker@2.x-tests.ts | 0 5 files changed, 111 insertions(+), 27 deletions(-) create mode 100644 types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts rename types/{bootstrap-colorpicker@2.x => bootstrap-colorpicker-v2}/index.d.ts (88%) rename types/{bootstrap-colorpicker@2.x => bootstrap-colorpicker-v2}/tsconfig.json (90%) rename types/{bootstrap-colorpicker@2.x => bootstrap-colorpicker-v2}/tslint.json (100%) delete mode 100644 types/bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts diff --git a/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts b/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts new file mode 100644 index 0000000000..7869da99c9 --- /dev/null +++ b/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts @@ -0,0 +1,77 @@ +$(() => { + $('#cp1').colorpicker(); + + $('#cp2').colorpicker(); + + $('#cp3').colorpicker({ + color: '#AA3399', + format: 'rgb' + }); + + $('#cp4').colorpicker().on('changeColor', (e) => { + $('body')[0].style.backgroundColor = e.color.toString('rgba'); + }); + + $('#cp5').colorpicker({ + color: "transparent", + format: "hex" + }); + + $('#cp6').colorpicker({ + color: "#88cc33", + horizontal: true + }); + + $('#cp7').colorpicker({ + color: '#ffaa00', + container: true, + inline: true + }); + + $('#cp8').colorpicker({ + colorSelectors: { + 'black': '#000000', + 'white': '#ffffff', + 'red': '#FF0000', + 'default': '#777777', + 'primary': '#337ab7', + 'success': '#5cb85c', + 'info': '#5bc0de', + 'warning': '#f0ad4e', + 'danger': '#d9534f' + } + }); + + $('#cp9').colorpicker({ + customClass: 'colorpicker-2x', + sliders: { + saturation: { + maxLeft: 200, + maxTop: 200 + }, + hue: { + maxTop: 200 + }, + alpha: { + maxTop: 200 + } + } + }); + + $(".disable-button").click((e) => { + e.preventDefault(); + + $("#cp10").colorpicker('disable'); + }); + + $(".enable-button").click((e) => { + e.preventDefault(); + + $("#cp10").colorpicker('enable'); + }); + + $('#cp10').colorpicker(); + + + $('#cp11').colorpicker(); +}); \ No newline at end of file diff --git a/types/bootstrap-colorpicker@2.x/index.d.ts b/types/bootstrap-colorpicker-v2/index.d.ts similarity index 88% rename from types/bootstrap-colorpicker@2.x/index.d.ts rename to types/bootstrap-colorpicker-v2/index.d.ts index 222b939b89..e04e8706f2 100644 --- a/types/bootstrap-colorpicker@2.x/index.d.ts +++ b/types/bootstrap-colorpicker-v2/index.d.ts @@ -5,13 +5,15 @@ /// +type ColorFormat = false | 'hex' | 'rgb' | 'rgba' + type ColorPickerAlignOptions = 'right' | 'left'; -type ColorPickerEvents = 'create' | - 'showPicker' | - 'hidePicker' | - 'changeColor' | - 'disable' | +type ColorPickerEvents = 'create' | + 'showPicker' | + 'hidePicker' | + 'changeColor' | + 'disable' | 'enable' | 'destroy' @@ -24,106 +26,106 @@ interface ColorPickerOptions { * * Default: false */ - format: string; + format?: ColorFormat; /** * If not false, sets the color to this value. * * Default: false */ - color: string; + color?: string; /** * If not false, the picker will be contained inside this element, otherwise it will be appended to the document body. * * Default: false */ - container: string | JQuery; + container?: boolean; /** * Children selector for the component or element that trigger the colorpicker and which background color will change (needs an inner element). * * Default: '.add-on, .input-group-addon' */ - component: string | JQuery; + component?: string | JQuery; /** * Children selector for the input that will store the picker selected value. * * Default: 'input' */ - input: string | JQuery; + input?: string | JQuery; /** * If true, put a '#' (number sign) before hex strings. * * Default: true */ - hexNumberSignPrefix: boolean; + hexNumberSignPrefix?: boolean; /** * If true, the hue and alpha channel bars will be rendered horizontally, above the saturation selector. * * Default: false */ - horizontal: boolean; + horizontal?: boolean; /** * If true, forces to show the colorpicker as an inline element. * * Default: false */ - inline: boolean; + inline?: boolean; /** * Vertical sliders configuration (read source code if you really need to tweak this). */ - sliders: object; + sliders?: object; /** * Horizontal sliders configuration (read source code if you really need to tweak this). */ - slidersHorz: object; + slidersHorz?: object; /** * Customizes the default colorpicker HTML template. */ - template: string; + template?: string; /** * By default, the colorpicker is aligned to the right of the input. If you need to switch it to the left, set align to 'left'. * * Default: 'right' */ - align: ColorPickerAlignOptions; + align?: ColorPickerAlignOptions; /** * Adds this class to the colorpicker widget. * * Default: null */ - customClass: string; + customClass?: string; /** * List of pre selected colors (hex format). If you choose one of these colors, the alias is returned instead of the hex code. * * Default: null */ - colorSelectors: object; + colorSelectors?: object; /** * Fallback color string that will be applied when the color failed to be parsed. If null, it will keep the current color if any. * * Default: null */ - fallbackColor: string; + fallbackColor?: string; /** * Fallback color format (e.g. when not specified or for alias mode, when selecting non aliased colors) * * Default: hex */ - fallbackFormat: string; + fallbackFormat?: string; } interface Color { @@ -133,8 +135,8 @@ interface Color { hexNumberSignPrefix: boolean; origFormat: string; predefinedColors: {}; - value: { - h: number; + value: { + h: number; s: number; b: number; a: number; @@ -179,6 +181,11 @@ interface Color { * Returns a hash with HSLA values. */ toHSL(): string; + + /** + * Returns current color as string in specified format. + */ + toString(format: ColorFormat): string; } interface ColorPicker { @@ -193,8 +200,8 @@ interface ColorPicker { picker: JQuery; } -interface ColorPickerEventObject { - +interface ColorPickerEventObject extends JQueryEventObject { + color: Color; } interface JQuery { @@ -202,7 +209,7 @@ interface JQuery { * Initializes an colorpicker. */ colorpicker(): JQuery; - + /** * Initializes an colorpicker. */ diff --git a/types/bootstrap-colorpicker@2.x/tsconfig.json b/types/bootstrap-colorpicker-v2/tsconfig.json similarity index 90% rename from types/bootstrap-colorpicker@2.x/tsconfig.json rename to types/bootstrap-colorpicker-v2/tsconfig.json index 61299349f7..e734e0a2ca 100644 --- a/types/bootstrap-colorpicker@2.x/tsconfig.json +++ b/types/bootstrap-colorpicker-v2/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "bootstrap-colorpicker@2.5.3-tests.ts" + "bootstrap-colorpicker-v2-tests.ts" ] } diff --git a/types/bootstrap-colorpicker@2.x/tslint.json b/types/bootstrap-colorpicker-v2/tslint.json similarity index 100% rename from types/bootstrap-colorpicker@2.x/tslint.json rename to types/bootstrap-colorpicker-v2/tslint.json diff --git a/types/bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts b/types/bootstrap-colorpicker@2.x/bootstrap-colorpicker@2.x-tests.ts deleted file mode 100644 index e69de29bb2..0000000000 From b6df4207a3252fb5d76d3c92e1759bec1d0f5f15 Mon Sep 17 00:00:00 2001 From: BlischkeFlorian <46778403+BlischkeFlorian@users.noreply.github.com> Date: Thu, 17 Jan 2019 10:30:43 +0100 Subject: [PATCH 030/312] Update index.d.ts added missing timeout parameter for options interface --- types/jquery.soap/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/jquery.soap/index.d.ts b/types/jquery.soap/index.d.ts index 36674a677b..5223244cb0 100644 --- a/types/jquery.soap/index.d.ts +++ b/types/jquery.soap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery.SOAP 1.6.7 +// Type definitions for jQuery.SOAP 1.7.3 // Project: https://github.com/doedje/jquery.soap // Definitions by: Roland Greim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ @@ -72,6 +72,7 @@ declare namespace JQuerySOAP { SOAPHeader?: Object; statusCode?: Object; success?: (SOAPResponse: SOAPResponse) => void; + timeout: number; url?: string; wss?: Object; } From 270f8b01502de94a2cbba5487820cff418ba74c9 Mon Sep 17 00:00:00 2001 From: BlischkeFlorian <46778403+BlischkeFlorian@users.noreply.github.com> Date: Thu, 17 Jan 2019 12:03:47 +0100 Subject: [PATCH 031/312] Update index.d.ts made timeout optional --- types/jquery.soap/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jquery.soap/index.d.ts b/types/jquery.soap/index.d.ts index 5223244cb0..f511d05575 100644 --- a/types/jquery.soap/index.d.ts +++ b/types/jquery.soap/index.d.ts @@ -72,7 +72,7 @@ declare namespace JQuerySOAP { SOAPHeader?: Object; statusCode?: Object; success?: (SOAPResponse: SOAPResponse) => void; - timeout: number; + timeout?: number; url?: string; wss?: Object; } From 457e3f9b7aaa6311f966d2492518a768d5b280f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20B=C3=A4r?= Date: Thu, 17 Jan 2019 17:29:03 +0100 Subject: [PATCH 032/312] Export the new dexpect const instead of expect to avoid exporting the global expect of another module. --- types/detox/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index de74163bf1..8ed9d4a9e8 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -8,6 +8,7 @@ declare global { const device: Detox.Device; const element: Detox.Element; const waitFor: Detox.WaitFor; + const dexpect: Detox.Expect>; const expect: Detox.Expect>; const by: Detox.Matchers; @@ -434,4 +435,4 @@ declare global { } } -export { by, detox, device, element, expect, waitFor }; +export { by, detox, device, element, dexpect as expect, waitFor }; From 50385d23490003b86548b8b58a359b6b38510099 Mon Sep 17 00:00:00 2001 From: Aleksandar Manukov <34056917+aleksandar-manukov@users.noreply.github.com> Date: Thu, 17 Jan 2019 21:19:45 +0200 Subject: [PATCH 033/312] Add TipeScript version in index.d.ts and change tslint.json --- .../bootstrap-colorpicker-v2-tests.ts | 26 +++++++++---------- types/bootstrap-colorpicker-v2/index.d.ts | 9 ++++--- types/bootstrap-colorpicker-v2/tsconfig.json | 4 ++- types/bootstrap-colorpicker-v2/tslint.json | 10 ++++++- 4 files changed, 30 insertions(+), 19 deletions(-) diff --git a/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts b/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts index 7869da99c9..a8be275b39 100644 --- a/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts +++ b/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts @@ -30,15 +30,15 @@ $(() => { $('#cp8').colorpicker({ colorSelectors: { - 'black': '#000000', - 'white': '#ffffff', - 'red': '#FF0000', - 'default': '#777777', - 'primary': '#337ab7', - 'success': '#5cb85c', - 'info': '#5bc0de', - 'warning': '#f0ad4e', - 'danger': '#d9534f' + black: '#000000', + white: '#ffffff', + red: '#FF0000', + default: '#777777', + primary: '#337ab7', + success: '#5cb85c', + info: '#5bc0de', + warning: '#f0ad4e', + danger: '#d9534f' } }); @@ -58,16 +58,16 @@ $(() => { } }); - $(".disable-button").click((e) => { + $('.disable-button').click((e) => { e.preventDefault(); - $("#cp10").colorpicker('disable'); + $('#cp10').colorpicker('disable'); }); - $(".enable-button").click((e) => { + $('.enable-button').click((e) => { e.preventDefault(); - $("#cp10").colorpicker('enable'); + $('#cp10').colorpicker('enable'); }); $('#cp10').colorpicker(); diff --git a/types/bootstrap-colorpicker-v2/index.d.ts b/types/bootstrap-colorpicker-v2/index.d.ts index e04e8706f2..327802513b 100644 --- a/types/bootstrap-colorpicker-v2/index.d.ts +++ b/types/bootstrap-colorpicker-v2/index.d.ts @@ -1,11 +1,12 @@ -// Type definitions for bootstrap-colorpicker 2.5.3 +// Type definitions for bootstrap-colorpicker 2.5 // Project: https://github.com/farbelous/bootstrap-colorpicker/tree/v2.x // Definitions by: Aleksandar Manukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// -type ColorFormat = false | 'hex' | 'rgb' | 'rgba' +type ColorFormat = 'hex' | 'rgb' | 'rgba'; type ColorPickerAlignOptions = 'right' | 'left'; @@ -15,7 +16,7 @@ type ColorPickerEvents = 'create' | 'changeColor' | 'disable' | 'enable' | - 'destroy' + 'destroy'; /** * You can set colorpicker options either as a plugin parameter or data-* attributes @@ -140,7 +141,7 @@ interface Color { s: number; b: number; a: number; - } + }; /** * Set a new color. The value is parsed and tries to do a quess on the format. diff --git a/types/bootstrap-colorpicker-v2/tsconfig.json b/types/bootstrap-colorpicker-v2/tsconfig.json index e734e0a2ca..7b9bf6cb2b 100644 --- a/types/bootstrap-colorpicker-v2/tsconfig.json +++ b/types/bootstrap-colorpicker-v2/tsconfig.json @@ -2,11 +2,13 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/bootstrap-colorpicker-v2/tslint.json b/types/bootstrap-colorpicker-v2/tslint.json index 3db14f85ea..8be13c2695 100644 --- a/types/bootstrap-colorpicker-v2/tslint.json +++ b/types/bootstrap-colorpicker-v2/tslint.json @@ -1 +1,9 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-consecutive-blank-lines": false, + "eofline": false, + "unified-signatures": false, + "no-trailing-whitespace": [true, "ignore-comments"] + } +} From ae852459aab51df79e22c6849781c87c942bb6a3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 17 Jan 2019 15:42:08 -0800 Subject: [PATCH 034/312] Update tsconfig.json --- types/forge-apis/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/forge-apis/tsconfig.json b/types/forge-apis/tsconfig.json index 1b591ad13e..3e026ae2b1 100644 --- a/types/forge-apis/tsconfig.json +++ b/types/forge-apis/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "lib": [ "es6", - "dom" + "dom" ], "noImplicitAny": true, "noImplicitThis": true, From 833f1e3214bc93876e6112eafac9ddf8c6095271 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 21 Jan 2019 00:12:24 +0100 Subject: [PATCH 035/312] [diff] move v3 to sub-dir --- types/diff/{ => v3}/diff-tests.ts | 0 types/diff/{ => v3}/index.d.ts | 0 types/diff/{ => v3}/tsconfig.json | 11 ++++++++--- types/diff/{ => v3}/tslint.json | 0 4 files changed, 8 insertions(+), 3 deletions(-) rename types/diff/{ => v3}/diff-tests.ts (100%) rename types/diff/{ => v3}/index.d.ts (100%) rename types/diff/{ => v3}/tsconfig.json (76%) rename types/diff/{ => v3}/tslint.json (100%) diff --git a/types/diff/diff-tests.ts b/types/diff/v3/diff-tests.ts similarity index 100% rename from types/diff/diff-tests.ts rename to types/diff/v3/diff-tests.ts diff --git a/types/diff/index.d.ts b/types/diff/v3/index.d.ts similarity index 100% rename from types/diff/index.d.ts rename to types/diff/v3/index.d.ts diff --git a/types/diff/tsconfig.json b/types/diff/v3/tsconfig.json similarity index 76% rename from types/diff/tsconfig.json rename to types/diff/v3/tsconfig.json index 9a1fdba840..92e1861ec8 100644 --- a/types/diff/tsconfig.json +++ b/types/diff/v3/tsconfig.json @@ -9,10 +9,15 @@ "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, - "baseUrl": "../", + "baseUrl": "../../", "typeRoots": [ - "../" + "../../" ], + "paths": { + "diff": [ + "diff/v3" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true @@ -21,4 +26,4 @@ "index.d.ts", "diff-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/diff/tslint.json b/types/diff/v3/tslint.json similarity index 100% rename from types/diff/tslint.json rename to types/diff/v3/tslint.json From a33191a1c65d50c6ba016f45a18a17126c864d21 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 21 Jan 2019 01:07:45 +0100 Subject: [PATCH 036/312] [diff] Add types for v4 --- types/diff/diff-tests.ts | 121 ++++++++++++ types/diff/index.d.ts | 402 +++++++++++++++++++++++++++++++++++++++ types/diff/tsconfig.json | 23 +++ types/diff/tslint.json | 1 + 4 files changed, 547 insertions(+) create mode 100644 types/diff/diff-tests.ts create mode 100644 types/diff/index.d.ts create mode 100644 types/diff/tsconfig.json create mode 100644 types/diff/tslint.json diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts new file mode 100644 index 0000000000..845b307132 --- /dev/null +++ b/types/diff/diff-tests.ts @@ -0,0 +1,121 @@ +import * as diff from 'diff'; + +const one = 'beep boop'; +const other = 'beep boob blah'; + +let changes = diff.diffChars(one, other); +examineChanges(changes); + +// $ExpectType void +diff.diffChars(one, other, { + callback: (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined + }, +}); +// $ExpectType void +diff.diffChars(one, other, (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined +}); + +const diffArraysResult = diff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +diffArraysResult.forEach(result => { + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType string[] + result.count; // $ExpectType number | undefined +}); + +interface DiffObj { + value: number; +} +const a: DiffObj = { value: 0 }; +const b: DiffObj = { value: 1 }; +const c: DiffObj = { value: 2 }; +const d: DiffObj = { value: 3 }; +const arrayOptions: diff.ArrayOptions = { + comparator: (left, right) => { + return left.value === right.value; + }, +}; +const arrayChanges = diff.diffArrays([a, b, c], [a, b, d], arrayOptions); +arrayChanges.forEach(result => { + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType DiffObj[] + result.count; // $ExpectType number | undefined +}); + +// -------------------------- + +class LineDiffWithoutWhitespace extends diff.Diff { + tokenize(value: string): any { + return value.split(/^/m); + } + + equals(left: string, right: string): boolean { + return left.trim() === right.trim(); + } +} + +const obj = new LineDiffWithoutWhitespace(); +changes = obj.diff(one, other); +examineChanges(changes); + +function examineChanges(diff: diff.Change[]) { + diff.forEach(part => { + part.added; // $ExpectType boolean | undefined + part.removed; // $ExpectType boolean | undefined + part.value; // $ExpectType string + part.count; // $ExpectType number | undefined + }); +} + +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyPatch = diff.parsePatch( + diff.createTwoFilesPatch('oldFile.ts', 'newFile.ts', oldStr, newStr, 'old', 'new', { + context: 1, + }) + ); + + if ( + JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== + JSON.stringify(uniDiff, Object.keys(uniDiff).sort()) + ) { + throw new Error('Patch did not match uniDiff'); + } +} +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])]; + diff.applyPatches([uniDiff], { + loadFile: (index, callback) => { + index; // $ExpectType ParsedDiff + callback(undefined, one); + }, + patched: (index, content) => { + index; // $ExpectType ParsedDiff + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + throw err; + } + + verifyApply.forEach(result => { + if (result !== newStr) { + throw new Error('Result did not match newStr'); + } + }); + }, + }); +} + +const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', { + context: 1, +}); +verifyPatchMethods(one, other, uniDiffPatch); + +const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 }); +const uniDiffApply = diff.parsePatch(uniDiffStr)[0]; +verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts new file mode 100644 index 0000000000..fa0e4e2e3d --- /dev/null +++ b/types/diff/index.d.ts @@ -0,0 +1,402 @@ +// Type definitions for diff 4.0 +// Project: https://github.com/kpdecker/jsdiff +// Definitions by: vvakame +// szdc +// moc-yuto +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export as namespace Diff; + +export type Callback = (err: undefined, value?: Change[]) => void; + +export interface CallbackOptions { + /** + * Callback to call with the result instead of returning the result directly. + */ + callback: Callback; +} + +export interface BaseOptions { + /** + * `true` to ignore casing difference. + * @default false + */ + ignoreCase?: boolean; +} + +export interface WordsOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`. + */ + ignoreWhitespace?: boolean; +} + +export interface LinesOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`. + */ + ignoreWhitespace?: boolean; + + /** + * `true` to treat newline characters as separate tokens. This allows for changes to the newline structure + * to occur independently of the line content and to be treated as such. In general this is the more + * human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer + * friendly output. + */ + newlineIsToken?: boolean; +} + +export interface JsonOptions extends LinesOptions { + /** + * Replacer used to stringify the properties of the passed objects. + */ + stringifyReplacer?: (key: string, value: any) => any; + + /** + * The value to use when `undefined` values in the passed objects are encountered during stringification. + * Will only be used if `stringifyReplacer` option wasn't specified. + * @default undefined + */ + undefinedReplacement?: any; +} + +export interface ArrayOptions extends BaseOptions { + /** + * Comparator for custom equality checks. + */ + comparator?: (left: TLeft, right: TRight) => boolean; +} + +export interface PatchOptions extends LinesOptions { + /** + * Describes how many lines of context should be included. + * @default 4 + */ + context?: number; +} + +export interface ApplyPatchOptions { + /** + * Number of lines that are allowed to differ before rejecting a patch. + * @default 0 + */ + fuzzFactor?: number; + + /** + * Callback used to compare to given lines to determine if they should be considered equal when patching. + * Should return `false` if the lines should be rejected. + * + * @default strict equality + */ + compareLine?: ( + lineNumber: number, + line: string, + operation: '-' | ' ', + patchContent: string + ) => boolean; +} + +export interface ApplyPatchesOptions { + loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; + patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; + complete(err: any): void; +} + +export interface Change { + count?: number; + /** + * Text content. + */ + value: string; + /** + * `true` if the value was inserted into the new string. + */ + added?: boolean; + /** + * `true` if the value was removed from the old string. + */ + removed?: boolean; +} + +export interface ArrayChange { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; +} + +export interface ParsedDiff { + index?: string; + oldFileName?: string; + newFileName?: string; + oldHeader?: string; + newHeader?: string; + hunks: Hunk[]; +} + +export interface Hunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; +} + +export interface BestPath { + newPos: number; + componenets: Change[]; +} + +export class Diff { + diff( + oldString: string, + newString: string, + options?: Callback | (ArrayOptions & Partial) + ): Change[]; + + pushComponent(components: Change[], added: boolean, removed: boolean): void; + + extractCommon( + basePath: BestPath, + newString: string, + oldString: string, + diagonalPath: number + ): number; + + equals(left: any, right: any): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] +} + +/** + * Diffs two blocks of text, comparing character by character. + * + * @returns A list of change objects. + */ +export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffChars( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, ignoring whitespace. + * + * @returns A list of change objects. + */ +export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[]; +export function diffWords( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, treating whitespace as significant. + * + * @returns A list of change objects. + */ +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options?: WordsOptions +): Change[]; +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line. + * + * @returns A list of change objects. + */ +export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. + * + * @returns A list of change objects. + */ +export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffTrimmedLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing sentence by sentence. + * + * @returns A list of change objects. + */ +export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffSentences( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing CSS tokens. + * + * @returns A list of change objects. + */ +export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffCss( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter + * in this comparison. + * + * @returns A list of change objects. + */ +export function diffJson( + oldObj: string | object, + newObj: string | object, + options?: JsonOptions +): Change[]; +export function diffJson( + oldObj: string | object, + newObj: string | object, + options: Callback | (JsonOptions & CallbackOptions) +): void; + +/** + * Diffs two arrays, comparing each item for strict equality (`===`). + * + * @returns A list of change objects. + */ +export function diffArrays( + oldArr: TOld[], + newArr: TNew[], + options?: ArrayOptions +): Array>; + +/** + * Creates a unified diff patch. + * + * @param oldFileName String to be output in the filename section of the patch for the removals. + * @param newFileName String to be output in the filename section of the patch for the additions. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createTwoFilesPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * Creates a unified diff patch. + * Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`. + * + * @param fileName String to be output in the filename section. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createPatch( + fileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing. + * Parameters are the same as `createTwoFilesPatch()`. + * + * @param oldFileName String to be output in the `oldFileName` hunk property. + * @param newFileName String to be output in the `newFileName` hunk property. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the `oldHeader` hunk property. + * @param newHeader Additional information to include in the `newHeader` hunk property. + * @returns An object with an array of hunk objects. + */ +export function structuredPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): ParsedDiff; + +/** + * Applies a unified diff patch. + * + * @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods. + * @returns A string containing new version of provided data. + */ +export function applyPatch( + source: string, + patch: string | ParsedDiff | [ParsedDiff], + options?: ApplyPatchOptions +): string; + +/** + * Applies one or more patches. + * This method will iterate over the contents of the patch and apply to data provided through callbacks. + * + * The general flow for each patch index is: + * + * 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file + * and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be + * the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback. + * Passing an `err` will terminate further patch execution. + * 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void; + +/** + * Parses a patch into structured data. + * + * @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method. + */ +export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[]; + +/** + * Converts a list of changes to a serialized XML format. + */ +export function convertChangesToXML(changes: Change[]): string; + +/** + * Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format. + */ +export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>; + +export function merge(mine: string, theirs: string, base: string): ParsedDiff; + +export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; diff --git a/types/diff/tsconfig.json b/types/diff/tsconfig.json new file mode 100644 index 0000000000..b32089d091 --- /dev/null +++ b/types/diff/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", + "diff-tests.ts" + ] +} diff --git a/types/diff/tslint.json b/types/diff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/diff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 243426f9854ea97c8a5cc6740252d40841efd23f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20B=C3=A4r?= Date: Mon, 21 Jan 2019 16:06:11 +0100 Subject: [PATCH 037/312] Add comment for new dexpect constant. --- types/detox/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index 8ed9d4a9e8..bcf914fac4 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -8,6 +8,12 @@ declare global { const device: Detox.Device; const element: Detox.Element; const waitFor: Detox.WaitFor; + /** + * `dexpect` ("Detox-expect") intentionally has the same type as `expect`. + * `expect` conflicts with the global `expect` of jest and therefore + * exporting it doesn't work which is why `dexpect` was introduced. `expect` + * is kept for backwards compatibility. + */ const dexpect: Detox.Expect>; const expect: Detox.Expect>; const by: Detox.Matchers; From 60a39291a567b2bf7717fbba0766bb7f9d6db96a Mon Sep 17 00:00:00 2001 From: mpsijm Date: Mon, 21 Jan 2019 16:52:23 +0100 Subject: [PATCH 038/312] Make export config parameter optional (PDF, PNG) According to the example in the documentation, both `exportToPDF` and `exportToPNG` can be called without argument. See: https://docs.dhtmlx.com/gantt/api__gantt_exporttopdf.html https://docs.dhtmlx.com/gantt/api__gantt_exporttopng.html --- types/dhtmlxgantt/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index f2e322b0e3..5502cdcaf2 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1455,13 +1455,13 @@ interface GanttStatic { * exports a Gantt chart into the PDF format * @param _export_ an object with export settings (see the details) */ - exportToPDF(_export_: any): void; + exportToPDF(_export_?: any): void; /** * exports a Gantt chart into the PNG format * @param _export_ an object with export settings (see the details) */ - exportToPNG(_export_: any): void; + exportToPNG(_export_?: any): void; /** * returns all dependency loops in the chart @@ -2242,4 +2242,4 @@ declare module "gantt" { declare module "Gantt" { export = Gantt; -} \ No newline at end of file +} From 6ddef01c459560adf998727ab861429a1c8dbc20 Mon Sep 17 00:00:00 2001 From: denis Date: Mon, 21 Jan 2019 17:22:06 +0100 Subject: [PATCH 039/312] Linting Select2 v3 --- types/select2/v3/index.d.ts | 115 +++++++++++++++--------------- types/select2/v3/select2-tests.ts | 71 ++++++++++-------- types/select2/v3/tsconfig.json | 4 +- types/select2/v3/tslint.json | 72 +------------------ 4 files changed, 102 insertions(+), 160 deletions(-) diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 3c8fc11155..f4a0c01efb 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 - /// interface Select2QueryOptions { @@ -23,8 +22,8 @@ interface AjaxFunction { interface Select2AjaxOptions extends JQueryAjaxSettings { transport?: AjaxFunction; /** - * Url to make request to, Can be string or a function returning a string. - */ + * Url to make request to, Can be string or a function returning a string. + */ url?: any; dataType?: string; quietMillis?: number; @@ -93,77 +92,77 @@ interface Select2Plugin { (): JQuery; (it: IdTextPair): JQuery; - /** - * Get the id value of the current selection - */ + /** + * Get the id value of the current selection + */ (method: 'val'): any; - /** - * Set the id value of the current selection - * @params value Value to set the id to - * @params triggerChange Should a change event be triggered - */ + /** + * Set the id value of the current selection + * @params value Value to set the id to + * @params triggerChange Should a change event be triggered + */ (method: 'val', value: any, triggerChange?: boolean): any; - /** - * Get the data object of the current selection - */ + /** + * Get the data object of the current selection + */ (method: 'data'): any; - /** - * Set the data of the current selection - * @params value Object to set the data to - * @params triggerChange Should a change event be triggered - */ + /** + * Set the data of the current selection + * @params value Object to set the data to + * @params triggerChange Should a change event be triggered + */ (method: 'data', value: any, triggerChange?: boolean): any; - /** - * Whether it is open - */ + /** + * Whether it is open + */ (method: 'opened'): boolean; - /** - * Whether it is in focus - */ + /** + * Whether it is in focus + */ (method: 'isFocused'): boolean; - /** - * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. - */ + /** + * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. + */ (method: 'destroy'): JQuery; - /** - * Opens the dropdown - */ + /** + * Opens the dropdown + */ (method: 'open'): JQuery; - /** - * Closes the dropdown - */ + /** + * Closes the dropdown + */ (method: 'close'): JQuery; - /** - * Disables Select2 - */ + /** + * Disables Select2 + */ (method: 'disable'): JQuery; - /** - * Enables or disables Select2 and its underlying form component - * @param value True if it should be enabled false if it should be disabled - */ + /** + * Enables or disables Select2 and its underlying form component + * @param value True if it should be enabled false if it should be disabled + */ (method: 'enable', value?: boolean): JQuery; - /** - * Enable its focus - */ + /** + * Enable its focus + */ (method: 'focus'): JQuery; - /** - * Toggles readonly mode on Select2 and its underlying form component - * @param value True if it should be readonly false if it should be read write - */ + /** + * Toggles readonly mode on Select2 and its underlying form component + * @param value True if it should be readonly false if it should be read write + */ (method: 'readonly', value: boolean): JQuery; - /** - * Retrieves the main container element that wraps all of DOM added by Select2 - */ + /** + * Retrieves the main container element that wraps all of DOM added by Select2 + */ (method: 'container'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has started - */ + /** + * Notifies Select2 that a drag and drop sorting operation has started + */ (method: 'onSortStart'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has finished - */ + /** + * Notifies Select2 that a drag and drop sorting operation has finished + */ (method: 'onSortEnd'): JQuery; - /** + /** * Executes a new search using the provided value. Example: $("#tags").select2("search", "California") */ (method: 'search'): JQuery; diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index fe7f900e3d..d777f138ab 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -9,9 +9,9 @@ $("#e2_2").select2({ $("#e3").select2({ minimumInputLength: 2 }); -function format(state) { +function format(state: any) { if (!state.id) return state.text; - return "" + state.text; + return `${state.text}`; } $("#e4").select2({ formatResult: format, @@ -21,10 +21,10 @@ $("#e5").select2({ minimumInputLength: 1, query: function (query) { console.info('current element value:', query.element.val()); - var data = { results: [] }, i, j, s; - for (i = 1; i < 5; i++) { - s = ""; - for (j = 0; j < i; j++) { s = s + query.term; } + const data = { results: [] as IdTextPair[] }; + for (let i = 1; i < 5; i++) { + let s = ""; + for (let j = 0; j < i; j++) { s = s + query.term; } data.results.push({ id: query.term + i, text: s }); } } @@ -35,7 +35,7 @@ $("#e10").select2({ data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] }); -var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; +const data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; $("#e10_2").select2({ data: { results: data, text: 'tag' }, @@ -44,11 +44,20 @@ $("#e10_2").select2({ }); $("#e10_3").select2({ - data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, + data: { + results: data, + text: (item: {tag: string}) => { + console.log('called with', item); + return item.tag; + } + }, formatSelection: format, formatResult: format }); -var movieFormatResult, movieFormatSelection; + +let movieFormatResult; +let movieFormatSelection; + $("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, @@ -75,7 +84,7 @@ $("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, ajax: { - url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, + url: () => "http://api.rottentomatoes.com/api/public/v1.0/movies.json", dataType: 'jsonp', data: function (term, page) { return { @@ -131,7 +140,7 @@ $("#e7").select2({ }; }, results: function (data, page) { - var more = (page * 10) < data.total; + const more = (page * 10) < data.total; return { results: data.movies, more: more }; } }, @@ -140,7 +149,7 @@ $("#e7").select2({ dropdownCssClass: "bigdrop" }); -function sort(elements) { +function sort(elements: any) { return elements.sort(); } @@ -170,8 +179,8 @@ $("#e11_2").select2({ multiple: true, data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] }); -function log(e) { - var item = $("
  • " + e + "
  • "); +function log(e: string) { + const item = $(`
  • ${e}
  • `); $("#events_11").append(item); item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); } @@ -201,7 +210,7 @@ $("#e16_2").select2(); $("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); $("#e16_disable").click(function () { $("#e16,#e16_2").select2("enable", false); }); $("#e17").select2({ - matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } + matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) === 0; } }); $("#e17_2").select2({ matcher: function (term, text, opt) { @@ -210,22 +219,26 @@ $("#e17_2").select2({ } }); $("#e18,#e18_2").select2(); -alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); -$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { - return currentSearchTerm; -}}); +alert("Selected value is: " + $("#e8").select2("val")); +$("#e8").select2("val", {id: "CA", text: "Califoria"}); -$('#e20').select2({ - tokenizer: (textInput, selection, selectCallback, options) => { - if (options.dropdownAutoWidth) { - selectCallback(); - return null; - } else if (options.allowClear) { - selectCallback(textInput + '_'); - return textInput + '_'; +$("#e1").select2({ + nextSearchTerm: (selectedObject: object, currentSearchTerm: string) => { + return currentSearchTerm; + } +}); + +$("#id").select2({ + tokenizer: (textInput, selection, selectCallback, options) => { + if (options.dropdownAutoWidth) { + selectCallback(); + return null; + } else if (options.allowClear) { + selectCallback(textInput + '_'); + return textInput + '_'; + } + selection.push('extra'); } - selection.push('extra'); - } }); $("#e8").select2("val"); diff --git a/types/select2/v3/tsconfig.json b/types/select2/v3/tsconfig.json index 8b8f30ed05..aeb9f31a86 100644 --- a/types/select2/v3/tsconfig.json +++ b/types/select2/v3/tsconfig.json @@ -5,8 +5,8 @@ "es6", "dom" ], - "noImplicitAny": false, - "noImplicitThis": false, + "noImplicitAny": true, + "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../../", diff --git a/types/select2/v3/tslint.json b/types/select2/v3/tslint.json index a41bf5d19a..fdbd83d321 100644 --- a/types/select2/v3/tslint.json +++ b/types/select2/v3/tslint.json @@ -1,79 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "unified-signatures": false } } From 57b4f84cee66a1df5219faaeabadf6c4942b4429 Mon Sep 17 00:00:00 2001 From: Glen Mailer Date: Mon, 21 Jan 2019 16:53:36 +0000 Subject: [PATCH 040/312] watchpack: startTime is an optional parameter --- types/watchpack/index.d.ts | 2 +- types/watchpack/watchpack-tests.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/watchpack/index.d.ts b/types/watchpack/index.d.ts index 880e0d8a6d..4ef4ad2e67 100644 --- a/types/watchpack/index.d.ts +++ b/types/watchpack/index.d.ts @@ -23,7 +23,7 @@ declare class Watchpack extends EventEmitter { constructor(options: Watchpack.WatchOptions); - watch(files: string[], directories: string[], startTime: number): void; + watch(files: string[], directories: string[], startTime?: number): void; close(): void; diff --git a/types/watchpack/watchpack-tests.ts b/types/watchpack/watchpack-tests.ts index 7ae28bc514..f3eb459aef 100644 --- a/types/watchpack/watchpack-tests.ts +++ b/types/watchpack/watchpack-tests.ts @@ -2,6 +2,7 @@ import Watchpack = require('watchpack'); const watch = new Watchpack({}); watch.watch(['test.js'], ['lib/'], 1000); +watch.watch(['test.js'], ['lib/']); let time: number; time = watch.getTimes()['test.js']; From e34d7934c43f7f576c2a3059469cb08386391538 Mon Sep 17 00:00:00 2001 From: denis Date: Mon, 21 Jan 2019 19:06:47 +0100 Subject: [PATCH 041/312] more --- types/select2/v3/select2-tests.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index d777f138ab..4a0a496e13 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -185,7 +185,6 @@ function log(e: string) { item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); } $("#e11") - // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) .on("open", function () { log("open"); }); $("#e11_2") @@ -234,7 +233,7 @@ $("#id").select2({ selectCallback(); return null; } else if (options.allowClear) { - selectCallback(textInput + '_'); + selectCallback(textInput + '_'); return textInput + '_'; } selection.push('extra'); From 067504a0480407be58158ac461c93a5ef4b3270d Mon Sep 17 00:00:00 2001 From: Dobes Vandermeer Date: Mon, 21 Jan 2019 16:35:28 -0800 Subject: [PATCH 042/312] stripe: Mark subscription.plan optional This field now "Only set if the subscription contains a single plan." See https://stripe.com/docs/api/subscriptions/object#subscription_object-plan --- types/stripe/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 5ab2666e58..08b65a2155 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4642,9 +4642,10 @@ declare namespace Stripe { items: IList; /** - * Hash describing the plan the customer is subscribed to + * Hash describing the plan the customer is subscribed to. Only set if the subscription + * contains a single plan. */ - plan: plans.IPlan; + plan?: plans.IPlan | null; /** * The number of subscriptions for the associated plan From 295bba5b897094b0b1b36511ca3783f762a65f52 Mon Sep 17 00:00:00 2001 From: Christopher Baek Date: Thu, 17 Jan 2019 10:03:45 -0800 Subject: [PATCH 043/312] Fix `initialize` function name typo in mermaidAPI The function in `mermaidAPI` is currently misspelled as `initalize` when it should be `initialize`. --- types/mermaid/mermaid-tests.ts | 2 +- types/mermaid/mermaidAPI.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/mermaid/mermaid-tests.ts b/types/mermaid/mermaid-tests.ts index 6d5b218ce4..a94355fb67 100644 --- a/types/mermaid/mermaid-tests.ts +++ b/types/mermaid/mermaid-tests.ts @@ -13,7 +13,7 @@ mermaid.initialize(config); // mermaidAPI usage const { mermaidAPI } = mermaid; -mermaidAPI.initalize({}); +mermaidAPI.initialize({}); const element = document.querySelector("#graphDiv")!; diff --git a/types/mermaid/mermaidAPI.d.ts b/types/mermaid/mermaidAPI.d.ts index 11077d88c4..127a679dae 100644 --- a/types/mermaid/mermaidAPI.d.ts +++ b/types/mermaid/mermaidAPI.d.ts @@ -240,7 +240,7 @@ declare namespace mermaidAPI { function parse(text: string): any; - function initalize(options: Config): void; + function initialize(options: Config): void; function getConfig(): Config; } From 3724e7b7dab312bb0df758d1c4b7235dd9aaa5b6 Mon Sep 17 00:00:00 2001 From: Christian d'Heureuse Date: Tue, 22 Jan 2019 23:25:37 +0100 Subject: [PATCH 044/312] [generic-pool] correct numTestsPerEvictionRun --- types/generic-pool/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 80a3c0e9df..6bb537e9ba 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -43,7 +43,7 @@ export interface Options { priorityRange?: number; autostart?: boolean; evictionRunIntervalMillis?: number; - numTestsPerRun?: number; + numTestsPerEvictionRun?: number; softIdleTimeoutMillis?: number; idleTimeoutMillis?: number; } From f773744b8f9e4a10c94e223fd839975653000812 Mon Sep 17 00:00:00 2001 From: Christian d'Heureuse Date: Tue, 22 Jan 2019 23:28:48 +0100 Subject: [PATCH 045/312] [generic-pool] correct numTestsPerEvictionRun also in test program --- types/generic-pool/generic-pool-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 4b8a69aa93..28590def30 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -34,7 +34,7 @@ const opts = { priorityRange: 5, autostart: false, evictionRunIntervalMillis: 200, - numTestsPerRun: 3, + numTestsPerEvictionRun: 3, softIdleTimeoutMillis: 100, idleTimeoutMillis: 5000 }; From f29cf32e0f176bd5a97b29caf4ce2074c04a9629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcello=20Bast=C3=A9a-Forte?= Date: Tue, 22 Jan 2019 15:56:47 -0800 Subject: [PATCH 046/312] [react-event-listener] add `onSelectionChange` --- types/react-event-listener/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index b37566af5c..c739912108 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -193,6 +193,8 @@ export interface EventListenerProps { onSeekingCapture?(ev: Event): any; onSelect?(ev: UIEvent): any; onSelectCapture?(ev: UIEvent): any; + onSelectionChange?(ev: UIEvent): any; + onSelectionChangeCapture?(ev: UIEvent): any; onStalled?(ev: Event): any; onStalledCapture?(ev: Event): any; onStorage?(ev: StorageEvent): any; From b77f49bb76e3bb8a757e30e348000f069b8b6b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcello=20Baste=CC=81a-Forte?= Date: Tue, 22 Jan 2019 16:08:26 -0800 Subject: [PATCH 047/312] update argument type to match MDN docs, add test --- types/react-event-listener/index.d.ts | 4 ++-- types/react-event-listener/react-event-listener-tests.tsx | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index c739912108..c3ff194394 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -193,8 +193,8 @@ export interface EventListenerProps { onSeekingCapture?(ev: Event): any; onSelect?(ev: UIEvent): any; onSelectCapture?(ev: UIEvent): any; - onSelectionChange?(ev: UIEvent): any; - onSelectionChangeCapture?(ev: UIEvent): any; + onSelectionChange?(ev: Event): any; + onSelectionChangeCapture?(ev: Event): any; onStalled?(ev: Event): any; onStalledCapture?(ev: Event): any; onStorage?(ev: StorageEvent): any; diff --git a/types/react-event-listener/react-event-listener-tests.tsx b/types/react-event-listener/react-event-listener-tests.tsx index 91c48b1047..8b9aae2c4d 100644 --- a/types/react-event-listener/react-event-listener-tests.tsx +++ b/types/react-event-listener/react-event-listener-tests.tsx @@ -4,3 +4,4 @@ import EventListener, { withOptions } from "react-event-listener"; { }} />; { }, { passive: true, capture: true })} />; { }}/>; + { }} />; From e3d21bbb0632734ebe8ec97d650b61bd12b88b03 Mon Sep 17 00:00:00 2001 From: Adam Krantz Date: Tue, 22 Jan 2019 16:30:30 -0800 Subject: [PATCH 048/312] Updated invocation context types --- .../custom-functions-runtime-tests.ts | 12 ++-- types/custom-functions-runtime/index.d.ts | 64 +++++++++++++++---- 2 files changed, 56 insertions(+), 20 deletions(-) diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 8f54ee4f5c..2104173734 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -17,10 +17,10 @@ async function getStockValues(ticker: string): Promise { async function getStockValuesCancellable( ticker: string, - handler: CustomFunctions.CancelableHandler + invocation: CustomFunctions.CancelableInvocation ): Promise { let shouldStop = false; - handler.onCanceled = () => (shouldStop = true); + invocation.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { @@ -33,7 +33,7 @@ async function getStockValuesCancellable( function stockPriceStream( ticker: string, - handler: CustomFunctions.StreamingHandler + invocation: CustomFunctions.StreamingInvocation ) { const updateFrequency = 10 /* milliseconds*/; let isPending = false; @@ -49,14 +49,14 @@ function stockPriceStream( try { const response = await fetch(url); const data = await response.json(); - handler.setResult(data.price); + invocation.setResult(data.price); } catch (error) { - handler.setResult(error); + invocation.setResult(error); } isPending = false; }, updateFrequency); - handler.onCanceled = () => { + invocation.onCanceled = () => { clearInterval(timer); }; } diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index 174308c131..237ad7c01b 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -15,41 +15,77 @@ Copyright (c) Microsoft Corporation */ declare namespace CustomFunctions { /** - * @beta * Associates the JavaScript function to the name given by the "id" property in the metadata JSON file. + * @beta */ function associate(id: string, functionObject: Function): void; /** - * @beta * Associates the JavaScript functions to the names given by the "id" properties in the metadata JSON file. + * @beta */ function associate(mappings: { [key: string]: Function }): void; /** - * A handler passed automatically as the last parameter - * to a streaming function. With this parameter, a - * function can use handler.setResult to set a cell value - * or hook into the handler.onCanceled event to - * to handle what happens when the function stops streaming. + * Provides information about the invocation of a custom function. * @beta */ - interface StreamingHandler extends CancelableHandler { + interface Invocation { /** - * Sets the returned result for a streaming custom function. - * @beta + * The cell address where the function is being called, if requested, otherwise undefined. + * + * To request the address for the function, in the metadata JSON file, the function options should specify: + * + * { + * "requiresAddress": "true" + * } + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag "@requiresAddress". */ - setResult: (value: T | Error) => void; + address?: string; } /** + * Provides information about the invocation of a cancelable custom function, + * and allows providing a function to be called when the function is canceled. * @beta - * CancelableHandler interface */ - interface CancelableHandler { + interface CancelableInvocation extends Invocation { /** - * Handles what should occur when a custom function is canceled. + * Event handler called when the custom function is canceled. * @beta */ onCanceled: () => void; } + + /** + * Provides information and events for the invocation of a cancelable custom function. + * @beta + * @deprecated Use CancelableInvocation instead. + */ + interface CancelableHandler extends CancelableInvocation { + } + + /** + * Provides information and events for the invocation of a streaming custom function whose result + * can change over time. Call setResult() one or more times to provide the result + * rather than returning a value from the function. + * @beta + */ + interface StreamingInvocation extends CancelableInvocation { + /** + * Sets the result for the custom function. May be called more than once. + * @beta + */ + setResult: (value: ResultType | Error) => void; + } + + /** + * Provides information and events for the invocation of a streaming custom function whose result + * can change over time. Call setResult() one or more times to provide the result + * rather than returning a value from the function. + * @beta + * @deprecated Use StreamingInvocation instead. + */ + interface StreamingHandler extends StreamingInvocation { + } } From a03b127a98d5db3831025d16b54fe7c87e8161ff Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Wed, 23 Jan 2019 02:04:17 +0000 Subject: [PATCH 049/312] [vinyl-fs] Add v0.3 and v1.0, remove watch() to match v2.4, remove .editorconfig and just use default 4 space indentation. --- types/vinyl-fs/.editorconfig | 3 - types/vinyl-fs/index.d.ts | 286 ++++----- types/vinyl-fs/tsconfig.json | 4 +- types/vinyl-fs/v0/index.d.ts | 201 ++++++ types/vinyl-fs/v0/tsconfig.json | 28 + types/vinyl-fs/v0/tslint.json | 6 + types/vinyl-fs/v0/vinyl-fs-tests.ts | 534 ++++++++++++++++ types/vinyl-fs/v1/index.d.ts | 245 ++++++++ types/vinyl-fs/v1/tsconfig.json | 28 + types/vinyl-fs/v1/tslint.json | 6 + types/vinyl-fs/v1/vinyl-fs-tests.ts | 919 ++++++++++++++++++++++++++++ types/vinyl-fs/vinyl-fs-tests.ts | 20 +- 12 files changed, 2109 insertions(+), 171 deletions(-) delete mode 100644 types/vinyl-fs/.editorconfig create mode 100644 types/vinyl-fs/v0/index.d.ts create mode 100644 types/vinyl-fs/v0/tsconfig.json create mode 100644 types/vinyl-fs/v0/tslint.json create mode 100644 types/vinyl-fs/v0/vinyl-fs-tests.ts create mode 100644 types/vinyl-fs/v1/index.d.ts create mode 100644 types/vinyl-fs/v1/tsconfig.json create mode 100644 types/vinyl-fs/v1/tslint.json create mode 100644 types/vinyl-fs/v1/vinyl-fs-tests.ts diff --git a/types/vinyl-fs/.editorconfig b/types/vinyl-fs/.editorconfig deleted file mode 100644 index 831139084b..0000000000 --- a/types/vinyl-fs/.editorconfig +++ /dev/null @@ -1,3 +0,0 @@ -[*.ts] -indent_style = space -indent_size = 3 diff --git a/types/vinyl-fs/index.d.ts b/types/vinyl-fs/index.d.ts index d35dd6bcef..f437276c4e 100644 --- a/types/vinyl-fs/index.d.ts +++ b/types/vinyl-fs/index.d.ts @@ -2,16 +2,17 @@ // Project: https://github.com/wearefractal/vinyl-fs // Definitions by: vvakame // remisery +// TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// declare global { - namespace NodeJS { - interface WritableStream { - write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; - } - } + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } } import * as _events from 'events'; @@ -19,128 +20,128 @@ import * as File from 'vinyl'; import * as globStream from 'glob-stream'; export interface SrcOptions extends globStream.Options { - /** Prevents stream from emitting an error when file not found. */ - allowEmpty?: boolean; + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; - /** Specifies the working directory the folder is relative to */ - cwd?: string; + /** Specifies the working directory the folder is relative to */ + cwd?: string; - /** - * Specifies the folder relative to the cwd - * This is used to determine the file names when saving in .dest() - * Default: where the glob begins - */ - base?: string; + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; - /** - * Setting this to false will make file.contents a paused stream - * If true it will buffer the file contents - * Default: true - */ - buffer?: boolean; + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; - /** - * The mode the directory should be created with. - * Default: the process mode - */ - dirMode?: number; + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; - /** - * Whether or not you want globs to match on dot files or not - * (e.g., `.gitignore`). - */ - dot?: boolean; + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; - /** - * Whether or not to recursively resolve symlinks to their targets. - * Setting to `false` to preserve them as symlinks and make `file.symlink` - * equal the original symlink's target path. - * Default: true - */ - followSymlinks?: boolean; + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; - /** - * Setting this to false will ignore the contents of the file and disable - * writing to disk to speed up operations - * Default: true - */ - read?: boolean; + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; - /** - * Whether or not the symlink should be relative or absolute. - * Default: false - */ - relative?: boolean; + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; - /** Only find files that have been modified since the time specified */ - since?: Date|number; + /** Only find files that have been modified since the time specified */ + since?: Date | number; - /** - * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` - * if you need the BOM for some reason. - */ - stripBOM?: boolean; + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; - /** - * Setting this to true will create a duplex stream, one that passes - * through items and emits globbed files. - * Default: false - */ - passthrough?: boolean; + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; - /** - * Setting this to true will enable sourcemaps. - * Default: false - */ - sourcemaps?: boolean; + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; - /** - * Whether or not to recursively resolve symlinks to their targets. Setting to false to - * preserve them as symlinks and make file.symlink equal the original symlink's target path. - * Default: false - */ - resolveSymlinks?: boolean; - /** - * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. - * Default: true - */ - removeBOM?: boolean; + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; } export interface DestOptions { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** - * Specify the mode the files should be created with - * Default is the mode of the input file (file.stat.mode) - * or the process mode if the input file has no mode property - */ - mode?: number|string; + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number | string; - /** Specify the mode the directory should be created with. Default is the process mode */ - dirMode?: number|string; + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number | string; - /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ - overwrite?: boolean; + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; - /** - * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if - * specified as true. Specifying a string path will write external sourcemaps at the given path. - */ - sourcemaps?: true | string; + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; - /** - * When creating a symlink, whether or not the created symlink should be relative. If false, - * the symlink will be absolute. Note: This option will be ignored if a junction is being created. - */ - relativeSymlinks?: boolean; + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; - /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ - useJunctions?: boolean; + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; } /** @@ -152,32 +153,6 @@ export interface DestOptions { */ export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; -/** - * This is just a glob-watcher - * - * @param globs Takes a glob string or an array of glob strings as the first argument - * Globs are executed in order, so negations should follow positive globs - * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) - */ -export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; - -/** - * This is just a glob-watcher - * - * @param globs Takes a glob string or an array of glob strings as the first argument - * Globs are executed in order, so negations should follow positive globs - * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) - */ -export function watch( - globs: string|string[], - opt?: { - interval?: number; - debounceDelay?: number; - cwd?: string; - maxListeners?(): number; - }, - cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; - /** * On write the stream will save the vinyl File to disk at the folder/cwd specified. * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. @@ -207,20 +182,20 @@ export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStr * cwd, base, and path will be overwritten to match the folder */ export function symlink(folder: string, opts?: { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** Specify the mode the directory should be created with. Default is the process mode */ - mode?: number|string; + /** Specify the mode the directory should be created with. Default is the process mode */ + mode?: number | string; - /** - * Specify the mode the directory should be created with - * Default is the process mode - */ - dirMode?: number + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number }): NodeJS.ReadWriteStream; /** @@ -229,17 +204,16 @@ export function symlink(folder: string, opts?: { * The file will be modified after being written to this stream: * cwd, base, and path will be overwritten to match the folder */ -export function symlink(getFolderPath: (File: File) => string, opts?: - { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; +export function symlink(getFolderPath: (File: File) => string, opts?: { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** - * Specify the mode the directory should be created with - * Default is the process mode - */ - dirMode?: number - }): NodeJS.ReadWriteStream; + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number +}): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/tsconfig.json b/types/vinyl-fs/tsconfig.json index 6f041838fd..7780364fc3 100644 --- a/types/vinyl-fs/tsconfig.json +++ b/types/vinyl-fs/tsconfig.json @@ -5,8 +5,8 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/vinyl-fs/v0/index.d.ts b/types/vinyl-fs/v0/index.d.ts new file mode 100644 index 0000000000..5b30adcea0 --- /dev/null +++ b/types/vinyl-fs/v0/index.d.ts @@ -0,0 +1,201 @@ +// Type definitions for vinyl-fs 0.3 +// Project: https://github.com/wearefractal/vinyl-fs +// Definitions by: vvakame +// remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } +} + +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +export interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; + + /** Specifies the working directory the folder is relative to */ + cwd?: string; + + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; + + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; + + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; + + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; + + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; + + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; + + /** Only find files that have been modified since the time specified */ + since?: Date|number; + + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; + + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; + + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; +} + +export interface DestOptions { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number|string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number|string; + + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; + + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; + + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; + + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; +} + +/** + * Gets files that match the glob and converts them into the vinyl format + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream + */ +export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?(): number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param folder destination folder + */ +export function dest(folder: string, opt?: DestOptions): NodeJS.ReadWriteStream; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param getFolderPath function that takes in a file and returns a folder path + */ +export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/v0/tsconfig.json b/types/vinyl-fs/v0/tsconfig.json new file mode 100644 index 0000000000..08ae9db69c --- /dev/null +++ b/types/vinyl-fs/v0/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "vinyl-fs": [ + "vinyl-fs/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} \ No newline at end of file diff --git a/types/vinyl-fs/v0/tslint.json b/types/vinyl-fs/v0/tslint.json new file mode 100644 index 0000000000..f2821adb2b --- /dev/null +++ b/types/vinyl-fs/v0/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-object-literal-type-assertion": false + } +} diff --git a/types/vinyl-fs/v0/vinyl-fs-tests.ts b/types/vinyl-fs/v0/vinyl-fs-tests.ts new file mode 100644 index 0000000000..b6aa418130 --- /dev/null +++ b/types/vinyl-fs/v0/vinyl-fs-tests.ts @@ -0,0 +1,534 @@ +// from src + +import * as vfs from 'vinyl-fs'; + +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); + +// import bufEqual = require('buffer-equal'); +declare const bufEqual: any; +// import through = require('through2'); +declare const through: any; +import File = require('vinyl'); +// const spies = require('./spy'); +declare const spies: any; + +// Stub mocha functions +const {describe, it, before, after, beforeEach, afterEach} = null as any as { + [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & {only: any, skip: any}; +}; + +// TODO: These aren't useful as types tests since they take `any`. +declare const should: ShouldStatic; +interface ShouldStatic { + exist(obj: any, desc?: string): void; + not: this; +} +declare global { + interface Object { + should: { equal(obj: any): void; }; + } +} + +declare const gulp: any; +let bufferStream: any; + +let dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +describe('source stream', () => { + it('should explode on invalid glob (empty)', done => { + let stream: any; + try { + stream = gulp.src(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (number)', done => { + let stream: any; + try { + stream = gulp.src(123); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (empty array)', done => { + let stream: any; + try { + stream = gulp.src([]); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: expectedPath, + contents: expectedContent + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/nothing.coffee"); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should glob a file with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with default settings and relative cwd', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a directory with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/wow"); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + buffered[0].isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/wow/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with with no contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + should.not.exist(buffered[0].contents); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, read: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with streaming contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isStream().should.equal(true); + + let contentBuffer = new Buffer([]); + const contentBufferStream = through(dataWrap((data: any) => { + contentBuffer = Buffer.concat([contentBuffer, data]); + })); + buffered[0].contents.pipe(contentBufferStream); + buffered[0].contents.once('end', () => { + bufEqual(contentBuffer, expectedContent); + done(); + }); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, buffer: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); +}); + +// from dest +// const vfs = require('../'); + +// const path = require('path'); +// const fs = require('graceful-fs'); +import rimraf = require('rimraf'); + +// const bufEqual = require('buffer-equal'); +// const through = require('through2'); +// const File = require('vinyl'); + +// const should = require('should'); +// require('mocha'); + +const wipeOut = (cb: any) => { + rimraf(path.join(__dirname, "./out-fixtures/"), cb); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +const realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('dest stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', done => { + let stream: any; + try { + stream = gulp.dest(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest(path.join(__dirname, "./out-fixtures/")); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should not write null files', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(false); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + fs.lstatSync(expectedPath).isDirectory().should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should allow piping multiple dests in streaming mode', done => { + const inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); + const inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); + const inputBase = path.join(__dirname, "./out-fixtures/"); + const srcPath = path.join(__dirname, "./fixtures/test.coffee"); + const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const content = fs.readFileSync(srcPath); + const rename = through.obj((file: any, _: any, next: any) => { + file.path = inputPath2; + this.push(file); + next(); + }); + + stream1.on('data', (file: any) => { + file.path.should.equal(inputPath1); + }); + + stream1.pipe(rename).pipe(stream2); + stream2.on('data', (file: any) => { + file.path.should.equal(inputPath2); + }).once('end', () => { + fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); + fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); + done(); + }); + + const file = new File({ + base: inputBase, + path: inputPath1, + cwd: __dirname, + contents: content + }); + + stream1.write(file); + stream1.end(); + }); +}); diff --git a/types/vinyl-fs/v1/index.d.ts b/types/vinyl-fs/v1/index.d.ts new file mode 100644 index 0000000000..2159567816 --- /dev/null +++ b/types/vinyl-fs/v1/index.d.ts @@ -0,0 +1,245 @@ +// Type definitions for vinyl-fs 1.0 +// Project: https://github.com/wearefractal/vinyl-fs +// Definitions by: vvakame +// remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } +} + +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +export interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; + + /** Specifies the working directory the folder is relative to */ + cwd?: string; + + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; + + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; + + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; + + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; + + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; + + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; + + /** Only find files that have been modified since the time specified */ + since?: Date|number; + + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; + + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; + + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; +} + +export interface DestOptions { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number|string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number|string; + + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; + + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; + + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; + + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; +} + +/** + * Gets files that match the glob and converts them into the vinyl format + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream + */ +export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?(): number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param folder destination folder + */ +export function dest(folder: string, opt?: DestOptions): NodeJS.ReadWriteStream; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param getFolderPath function that takes in a file and returns a folder path + */ +export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStream; + +/** + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd specified. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ +export function symlink(folder: string, opts?: { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + mode?: number|string; + + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number +}): NodeJS.ReadWriteStream; + +/** + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd generated from getFolderPath. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ +export function symlink(getFolderPath: (File: File) => string, opts?: + { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number + }): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/v1/tsconfig.json b/types/vinyl-fs/v1/tsconfig.json new file mode 100644 index 0000000000..4e7c14e299 --- /dev/null +++ b/types/vinyl-fs/v1/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "vinyl-fs": [ + "vinyl-fs/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} \ No newline at end of file diff --git a/types/vinyl-fs/v1/tslint.json b/types/vinyl-fs/v1/tslint.json new file mode 100644 index 0000000000..f2821adb2b --- /dev/null +++ b/types/vinyl-fs/v1/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-object-literal-type-assertion": false + } +} diff --git a/types/vinyl-fs/v1/vinyl-fs-tests.ts b/types/vinyl-fs/v1/vinyl-fs-tests.ts new file mode 100644 index 0000000000..aac3c4f49e --- /dev/null +++ b/types/vinyl-fs/v1/vinyl-fs-tests.ts @@ -0,0 +1,919 @@ +// from src + +import * as vfs from 'vinyl-fs'; + +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); + +// import bufEqual = require('buffer-equal'); +declare const bufEqual: any; +// import through = require('through2'); +declare const through: any; +import File = require('vinyl'); +// const spies = require('./spy'); +declare const spies: any; + +// Stub mocha functions +const {describe, it, before, after, beforeEach, afterEach} = null as any as { + [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & {only: any, skip: any}; +}; + +// TODO: These aren't useful as types tests since they take `any`. +declare const should: ShouldStatic; +interface ShouldStatic { + exist(obj: any, desc?: string): void; + not: this; +} +declare global { + interface Object { + should: { equal(obj: any): void; }; + } +} + +declare const gulp: any; +let bufferStream: any; + +let dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +describe('source stream', () => { + it('should explode on invalid glob (empty)', done => { + let stream: any; + try { + stream = gulp.src(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (number)', done => { + let stream: any; + try { + stream = gulp.src(123); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (empty array)', done => { + let stream: any; + try { + stream = gulp.src([]); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: expectedPath, + contents: expectedContent + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/nothing.coffee"); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should glob a file with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with default settings and relative cwd', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a directory with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/wow"); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + buffered[0].isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/wow/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with with no contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + should.not.exist(buffered[0].contents); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, read: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with streaming contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isStream().should.equal(true); + + let contentBuffer = new Buffer([]); + const contentBufferStream = through(dataWrap((data: any) => { + contentBuffer = Buffer.concat([contentBuffer, data]); + })); + buffered[0].contents.pipe(contentBufferStream); + buffered[0].contents.once('end', () => { + bufEqual(contentBuffer, expectedContent); + done(); + }); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, buffer: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); +}); + +// from dest +// const vfs = require('../'); + +// const path = require('path'); +// const fs = require('graceful-fs'); +import rimraf = require('rimraf'); + +// const bufEqual = require('buffer-equal'); +// const through = require('through2'); +// const File = require('vinyl'); + +// const should = require('should'); +// require('mocha'); + +let wipeOut = (cb: any) => { + rimraf(path.join(__dirname, "./out-fixtures/"), cb); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +let realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('dest stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', done => { + let stream: any; + try { + stream = gulp.dest(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest(path.join(__dirname, "./out-fixtures/")); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should not write null files', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(false); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + fs.lstatSync(expectedPath).isDirectory().should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should allow piping multiple dests in streaming mode', done => { + const inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); + const inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); + const inputBase = path.join(__dirname, "./out-fixtures/"); + const srcPath = path.join(__dirname, "./fixtures/test.coffee"); + const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const content = fs.readFileSync(srcPath); + const rename = through.obj((file: any, _: any, next: any) => { + file.path = inputPath2; + this.push(file); + next(); + }); + + stream1.on('data', (file: any) => { + file.path.should.equal(inputPath1); + }); + + stream1.pipe(rename).pipe(stream2); + stream2.on('data', (file: any) => { + file.path.should.equal(inputPath2); + }).once('end', () => { + fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); + fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); + done(); + }); + + const file = new File({ + base: inputBase, + path: inputPath1, + cwd: __dirname, + contents: content + }); + + stream1.write(file); + stream1.end(); + }); +}); + +// This test is from + +const chmodSpy = spies.chmodSpy; +const statSpy = spies.statSpy; + +wipeOut = (cb: any) => { + rimraf(path.join(__dirname, './out-fixtures/'), cb); + spies.setError('false'); + statSpy.reset(); + chmodSpy.reset(); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('symlink stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', (done: any) => { + let stream: any; + try { + stream = gulp.symlink(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.symlink(path.join(__dirname, './out-fixtures/')); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should make link to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with function and relative cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink(file => { + should.exist(file); + file.should.equal(expectedFile); + return './out-fixtures'; + }, { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/wow'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/wow'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.readlinkSync(expectedPath).should.equal(inputPath); + fs.lstatSync(expectedPath).isDirectory().should.equal(false); + fs.statSync(expectedPath).isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should use different modes for files and directories', done => { + const inputBase = path.join(__dirname, './fixtures'); + const inputPath = path.join(__dirname, './fixtures/wow/suchempty'); + const expectedBase = path.join(__dirname, './out-fixtures/wow'); + const expectedDirMode = parseInt("0755", 8); + const expectedFileMode = parseInt("0655", 8); + + const firstFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + stat: fs.statSync(inputPath) + }); + + const onEnd = () => { + realMode(fs.lstatSync(expectedBase).mode).should.equal(expectedDirMode); + realMode(buffered[0].stat.mode).should.equal(expectedFileMode); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { + cwd: __dirname, + mode: expectedFileMode, + dirMode: expectedDirMode + }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + + stream.pipe(bufferStream); + stream.write(firstFile); + stream.end(); + }); + + it('should report IO errors', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0722", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + fs.mkdirSync(expectedBase); + fs.chmodSync(expectedBase, 0); + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + stream.on('error', (err: any) => { + err.code.should.equal('EACCES'); + done(); + }); + stream.write(expectedFile); + }); + + ['end', 'finish'].forEach(eventName => { + it(`should emit ${eventName} event`, done => { + const srcPath = path.join(__dirname, './fixtures/test.coffee'); + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + stream.on(eventName, () => { + done(); + }); + + const file = new File({ + path: srcPath, + cwd: __dirname, + contents: new Buffer("1234567890") + }); + + stream.write(file); + stream.end(); + }); + }); + it('should check if it"s a vinyl file', () => { + const srcPath = path.join(__dirname, './fixtures/test.coffee'); + const options = { + path: srcPath, + cwd: __dirname, + contents: new Buffer("1234567890") + }; + const file = new File(options); + File.isVinyl(file).should.equal(true); + File.isVinyl(options).should.equal(false); + }); +}); diff --git a/types/vinyl-fs/vinyl-fs-tests.ts b/types/vinyl-fs/vinyl-fs-tests.ts index aac3c4f49e..18afe59744 100644 --- a/types/vinyl-fs/vinyl-fs-tests.ts +++ b/types/vinyl-fs/vinyl-fs-tests.ts @@ -3,13 +3,14 @@ import * as vfs from 'vinyl-fs'; import * as path from 'path'; -import * as fs from 'fs'; // require('graceful-fs'); +import * as fs from 'fs'; +import * as stream from 'stream'; // import bufEqual = require('buffer-equal'); declare const bufEqual: any; -// import through = require('through2'); -declare const through: any; +import gulp = require('gulp'); import File = require('vinyl'); +import through = require('through2'); // const spies = require('./spy'); declare const spies: any; @@ -30,8 +31,7 @@ declare global { } } -declare const gulp: any; -let bufferStream: any; +let bufferStream: stream.Transform; let dataWrap = (fn: any) => { return (data: any, enc: any, cb: any) => { @@ -44,7 +44,7 @@ describe('source stream', () => { it('should explode on invalid glob (empty)', done => { let stream: any; try { - stream = gulp.src(); + stream = ( gulp).src(); } catch (err) { should.exist(err); should.not.exist(stream); @@ -55,7 +55,7 @@ describe('source stream', () => { it('should explode on invalid glob (number)', done => { let stream: any; try { - stream = gulp.src(123); + stream = gulp.src( 123); } catch (err) { should.exist(err); should.not.exist(stream); @@ -243,7 +243,7 @@ describe('dest stream', () => { it('should explode on invalid folder', done => { let stream: any; try { - stream = gulp.dest(); + stream = ( gulp).dest(); } catch (err) { should.exist(err); should.not.exist(stream); @@ -502,7 +502,7 @@ describe('dest stream', () => { const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); const content = fs.readFileSync(srcPath); - const rename = through.obj((file: any, _: any, next: any) => { + const rename = through.obj(function t(this: stream.Transform, file: any, _: any, next: any) { file.path = inputPath2; this.push(file); next(); @@ -563,7 +563,7 @@ describe('symlink stream', () => { it('should explode on invalid folder', (done: any) => { let stream: any; try { - stream = gulp.symlink(); + stream = ( gulp).symlink(); } catch (err) { should.exist(err); should.not.exist(stream); From 7e615230a76cb220a8504c08ed59dc436f58277a Mon Sep 17 00:00:00 2001 From: Adam Krantz Date: Wed, 23 Jan 2019 06:18:47 -0800 Subject: [PATCH 050/312] Updated invocation context types --- types/custom-functions-runtime/index.d.ts | 33 +++++++++++++++-------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index 237ad7c01b..b2616dcf11 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Custom Functions 1.4 // Project: https://github.com/OfficeDev/office-js -// Definitions by: OfficeDev , Michael Zlatkovsky , Michelle Scharlock +// Definitions by: OfficeDev , +// Adam Krantz , +// Michael Zlatkovsky , +// Michelle Scharlock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -36,7 +39,7 @@ declare namespace CustomFunctions { * To request the address for the function, in the metadata JSON file, the function options should specify: * * { - * "requiresAddress": "true" + * "requiresAddress": true * } * * If the metadata JSON file is being generated from JSDoc comments, include the tag "@requiresAddress". @@ -45,9 +48,17 @@ declare namespace CustomFunctions { } /** - * Provides information about the invocation of a cancelable custom function, - * and allows providing a function to be called when the function is canceled. + * Provides information about the invocation of a cancelable custom function. + * A cancelable custom function can provide a handler for the onCanceled event. * @beta + * + * To indicate that a function is cancelable, in the metadata JSON file, the function options should specify: + * + * { + * "cancelable": true + * } + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag "@cancelable". */ interface CancelableInvocation extends Invocation { /** @@ -58,7 +69,7 @@ declare namespace CustomFunctions { } /** - * Provides information and events for the invocation of a cancelable custom function. + * Provides information about the invocation of a cancelable custom function. * @beta * @deprecated Use CancelableInvocation instead. */ @@ -66,9 +77,11 @@ declare namespace CustomFunctions { } /** - * Provides information and events for the invocation of a streaming custom function whose result - * can change over time. Call setResult() one or more times to provide the result - * rather than returning a value from the function. + * Provides information about the invocation of a streaming custom function. + * A streaming custom function can provide results which can change over time. + * + * Call setResult() one or more times to provide the result instead of returning + * a result from the function. * @beta */ interface StreamingInvocation extends CancelableInvocation { @@ -80,9 +93,7 @@ declare namespace CustomFunctions { } /** - * Provides information and events for the invocation of a streaming custom function whose result - * can change over time. Call setResult() one or more times to provide the result - * rather than returning a value from the function. + * Provides information about the invocation of a streaming custom function. * @beta * @deprecated Use StreamingInvocation instead. */ From 370b599cf5c51f151b297e9a2d5457e88252c03e Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Wed, 23 Jan 2019 22:28:56 +0800 Subject: [PATCH 051/312] Removing Viewer Definitions --- types/forge-apis/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts index c7fcdc3c5a..07dca58812 100644 --- a/types/forge-apis/index.d.ts +++ b/types/forge-apis/index.d.ts @@ -19,7 +19,6 @@ // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // -/// export class AuthClientTwoLegged { constructor(clientId: string, clientSecret: string, scope: string[]); From 58397a5e69bfb3244508397cefb17af609496a9e Mon Sep 17 00:00:00 2001 From: Bryan Huang Date: Wed, 23 Jan 2019 22:29:29 +0800 Subject: [PATCH 052/312] Delete viewer.d.ts --- types/forge-apis/src/viewer.d.ts | 485 ------------------------------- 1 file changed, 485 deletions(-) delete mode 100644 types/forge-apis/src/viewer.d.ts diff --git a/types/forge-apis/src/viewer.d.ts b/types/forge-apis/src/viewer.d.ts deleted file mode 100644 index 0b28cc720f..0000000000 --- a/types/forge-apis/src/viewer.d.ts +++ /dev/null @@ -1,485 +0,0 @@ -// -// Copyright (c) Autodesk, Inc. All rights reserved -// -// Permission to use, copy, modify, and distribute this software in -// object code form for any purpose and without fee is hereby granted, -// provided that the above copyright notice appears in all copies and -// that both that copyright notice and the limited warranty and -// restricted rights notice below appear in all supporting -// documentation. -// -// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. -// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF -// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. -// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE -// UNINTERRUPTED OR ERROR FREE. -// -/// - -declare namespace Autodesk { - namespace Viewing { - // events - let ESCAPE_EVENT: string; - let PROGRESS_UPDATE_EVENT: string; - let FULLSCREEN_MODE_EVENT: string; - let NAVIGATION_MODE_CHANGED_EVENT: string; - let VIEWER_STATE_RESTORED_EVENT: string; - let VIEWER_RESIZE_EVENT: string; - let VIEWER_UNINITIALIZED: string; - let MODEL_ROOT_LOADED_EVENT: string; - let GEOMETRY_LOADED_EVENT: string; - let TOOLBAR_CREATED_EVENT: string; - let OBJECT_TREE_CREATED_EVENT: string; - let OBJECT_TREE_UNAVAILABLE_EVENT: string; - let MODEL_UNLOADED_EVENT: string; - let SELECTION_CHANGED_EVENT: string; - let AGGREGATE_SELECTION_CHANGED_EVENT: string; - let ISOLATE_EVENT: string; - let HIDE_EVENT: string; - let SHOW_EVENT: string; - let HIGHLIGHT_EVENT: string; - let CAMERA_CHANGE_EVENT: string; - let EXPLODE_CHANGE_EVENT: string; - let CUTPLANES_CHANGE_EVENT: string; - let TOOL_CHANGE_EVENT: string; - let RENDER_OPTION_CHANGED_EVENT: string; - let LAYER_VISIBILITY_CHANGED_EVENT: string; - let RESET_EVENT: string; - let ANIMATION_READY_EVENT: string; - - enum SelectionMode { - LEAF_OBJECT, - FIRST_OBJECT, - LAST_OBJECT - } - - let theExtensionManager: ExtensionManager; - - interface InitializerOptions { - env?: string; - language?: string; - webGLHelpLink?: string; - getAccessToken?(callback?: (accessToken: string, expires?: number) => void): void; - refreshToken?(callback?: (accessToken: string, expires?: number) => void): void; - } - - function Initializer(options: InitializerOptions, callback?: () => void): void; - - class Document { - static load(documentId: string, successCallback: (doc: Document) => void, - errorCallback: (errorCode: number, errorMsg: string, messages: any[]) => void, accessControlProperties?: any): void; - static getSubItemsWithProperties(item: object, properties: Properties, recursive: boolean): object[]; - - acmSessionId: string; - - getRootItem(): object; - getViewablePath(item: object): string; - } - - class Extension { - viewer: Private.GuiViewer3D; - options: any; - constructor(viewer: Private.GuiViewer3D, options: any); - - load(): boolean; - unload(): boolean; - } - - class ExtensionManager { - registerExtension(extensionId: string, extension: any): boolean; - unregisterExtension(extensionId: string): boolean; - - getExtension(extensionId: string): any; - } - - class InstanceTree { - maxDepth: number; - nodeAccess: InstanceTreeAccess; - numHidden: number; - numOff: number; - objectCount: number; - - enumNodeChildren(node: any, callback: (dbId: number) => void, recursive?: boolean): void; - enumNodeFragments(node: any, callback: (fragId: number) => void, recursive?: boolean): void; - getChildCount(dbId: number): number; - getNodeBox(dbId: number, nodeBox: Float32Array): void; - getNodeParentId(dbId: number): number; - getRootId(): number; - setFlagGlobal(flag: any, value: any): void; - setFlagNode(dbId: number, flag: any, value: any): boolean; - } - - class InstanceTreeAccess { - children: any; - dbIdToIndex: any; - nameSuffixes: any; - names: any; - nodeBoxes: any; - nodes: any; - numNodes: number; - rootId: number; - strings: string[]; - visibleIds: number; - } - - interface InstanceTreeNode { - dbId: number; - name: string; - fragments: number[]; - children: InstanceTreeNode[]; - } - - class Model { - getBoundingBox(): THREE.Box3; - getBulkProperties(dbIds: number[], propFilter?: string[], successCallback?: (r: any) => void, errorCallback?: (err: any) => void): void; - getData(): any; - getFragmentList(): any; - getObjectTree(successCallback?: (result: InstanceTree) => void, errorCallback?: (err: any) => void): void; - getProperties(dbId: number, successCallback?: (r: PropertyResult) => void, errorCallback?: (err: any) => void): void; - getUnitScale(): number; - getUnitString(): number; - // search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; - search(text: string, successCallback: (r: number[]) => void, errorCallback?: (err: any) => void, attributeNames?: string[]): void; - clearThemingColors(): void; - - getInstanceTree(): InstanceTree; - visibilityManager: Private.VisibilityManager; - } - - interface PropertyResult { - dbId: number; - externalId?: string; - name?: string; - properties: Property[]; - } - - interface Property { - displayCategory: string; - displayName: string; - displayValue: string; - hidden: boolean; - type: number; - units: string; - } - - class Navigation { - getCamera(): any; - getEyeVector(): THREE.Vector3; - getFovMin(): number; - getFovMax(): number; - getPivotPoint(): THREE.Vector3; - setPivotPoint(pivot: THREE.Vector3): void; - getPosition(): THREE.Vector3; - setPosition(pos: THREE.Vector3): void; - getTarget(): THREE.Vector3; - setTarget(target: THREE.Vector3): void; - getScreenViewport(): ClientRect; - setScreenViewport(viewport: ClientRect): void; - setView(position: THREE.Vector3, target: THREE.Vector3): void; - setCameraUpVector(up: THREE.Vector): void; - } - - interface Properties { - type: string; - role: string; - } - - class ToolController { - activateTool(name: string): boolean; - deactivateTool(name: string): boolean; - registerTool(tool: any): boolean; - deregisterTool(tool: any): boolean; - getToolNames(): string[]; - getActiveToolName(): string; - } - - interface ToolInterface { - getCursor?(): string; - getName(): string; - getNames(): string[]; - register(): void; - deregister(): void; - activate(name: string, viewerApi?: Private.GuiViewer3D): void; - deactivate(name: string): void; - update(): boolean; - handleSingleClick?(event: MouseEvent, button: number): boolean; - handleDoubleClick?(event: MouseEvent, button: number): boolean; - handleSingleTap?(event: Event): boolean; - handleDoubleTap?(event: Event): boolean; - handleKeyDown?(event: KeyboardEvent, keyCode: number): boolean; - handleKeyUp?(event: KeyboardEvent, keyCode: number): boolean; - handleWheelInput?(delta: number): boolean; - handleButtonDown?(event: MouseEvent, button: number): boolean; - handleButtonUp?(event: MouseEvent, button: number): boolean; - handleMouseMove?(event: MouseEvent): boolean; - handleGesture?(event: Event): boolean; - handleBlur?(event: Event): boolean; - handleResize?(): void; - } - - class UnifiedCamera { - } - - interface ContextMenuCallbackStatus { - hasHidden: boolean; - hasSelected: boolean; - hasVisible: boolean; - numSelected: number; - } - - interface ContextMenuItem { - target: () => void; - title: string; - } - - class Viewer3D { - id: number; - - clearSelection(): void; - clearThemingColors(model: any): void; - clientToWorld(point: THREE.Vector3): THREE.Vector3; - createViewCube(): void; - displayViewCube(display: boolean): void; - fitToView(objectIds?: number[], model?: Model): boolean; - getHiddenNodes(): number[]; - getIsolatedNodes(): number[]; - getSelection(): number[]; - getSelectionCount(): number; - getSelectionVisibility(): { hasVisible: boolean, hasHidden: boolean }; - getState(filter?: any): any; - hide(node: number | number[]): void; - hideById(node: number): void; - isolate(node: number | number[]): void; - isolateById(dbIds: number | number[]): void; - registerContextMenuCallback(id: string, callback: (menu: ContextMenuItem[], status: ContextMenuCallbackStatus) => void): void; - resize(): void; - restoreState(state: any, filter?: any, immediate?: boolean): boolean; - search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; - select(dbIds: number | number[]): void; - setCutPlanes(planes: THREE.Vector4[]): void; - setSelectionMode(mode: SelectionMode): void; - setThemingColor(dbId: number, color: THREE.Vector4, model?: any): void; - setUp(config?: any): void; - setViewCube(face: string): void; - show(node: number | number[]): void; - showAll(): void; - tearDown(): void; - toggleSelect(dbid: number): void; - unregisterContextMenuCallback(id: string): void; - worldToClient(point: THREE.Vector3): THREE.Vector3; - } - - class ViewingUtilities { - getHitPoint(x: number, y: number): THREE.Vector3; - } - - namespace Private { - function getHtmlTemplate(url: string, callback: (error: string, content: string) => void): void; - - class GuiViewer3D extends Viewer3D { - constructor(container: HTMLElement, config?: object); - - canvas: HTMLCanvasElement; - container: Element; - toolController: ToolController; - impl: Viewer3DImpl; - model: Model; - navigation: Navigation; - - getCamera(): UnifiedCamera; - getToolbar(create: boolean): UI.ToolBar; - initialize(): any; - load(urn: string, sharedPropertyDbPath?: string, onSuccesfullCallback?: () => void, - onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; - loadModel(urn: string, options?: any, onSuccesfullCallback?: () => void, - onErrorCallback?: (errorCode: number, errorMessage: string, statusCode: number, statusText: string) => void): any; - start(path?: string, options?: object): any; - finish(): any; - setUsePivotAlways(value: boolean): any; - - setGroundShadow(param: boolean): void ; - setGroundReflection(param: boolean): void ; - setOptimizeNavigation(param: boolean): void ; - setQualityLevel(useSAO: boolean, useFXAA: boolean): void; - - loadExtension(extensionId: string, options?: object): boolean; - unloadExtension(extensionId: string): boolean; - getExtension(extensionId: string): Extension; - - addPanel(panel: UI.DockingPanel): boolean; - removePanel(panel: UI.DockingPanel): boolean; - resizePanels(options: any): void; - - addEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; - removeEventListener(event: string, callback: (event: any) => void, useCapture?: boolean): void; - } - - interface HitTestResult { - dbId: number; - face: THREE.Face3; - fragId: number; - intersectPoint: THREE.Vector3; - model: Model; - } - - namespace HudMessage { - function displayMessage(container: Element, messageSpec: { - msgTitleKey: string, - msgTitleDefault?: string, - messageKey: string, - messageDefaultValue?: string, - buttonText?: string, - checkboxChecked?: boolean - }, closeCallback?: (event: any) => void, buttonCallback?: (event: any) => void, checkboxCallback?: (event: any) => void): void; - - function dismiss(): boolean; - } - - class Viewer3DImpl { - constructor(thecanvas: any, theapi: any); - - visibilityManager: VisibilityManager; - - clientToViewport(clientX: number, clientY: number): THREE.Vector3; - hitTest(clientX: number, clientY: number, ignoreTransparent: boolean): HitTestResult; - hitTestViewport(vpVec: THREE.Vector3, ignoreTransparent: boolean): HitTestResult; - initialize(): void; - setLightPreset(index: number, force?: boolean): void; - viewportToClient(viewportX: number, viewportY: number): THREE.Vector3; - - getMaterials(): any; - getRenderProxy(model: Model, fragId: number): any; - sceneUpdated(param: boolean): void; - } - - class VisibilityManager { - constructor(viewerImpl: any, model: any); - - getHiddenNodes(): any; - getInstanceTree(): InstanceTree; - getIsolatedNodes(): any; - hide(node: number | object): void; - isNodeVisible(dbId: number): boolean; - isolate(node: number | object): void; - isolateMultiple(nodeList: any[]): void; - isolateNone(): void; - setAllVisibility(visible: boolean): void; - setVisibilityOnNode(node: number | object, visible: boolean): void; - setNodeOff(node: number | object, isOff: boolean): void; - show(node: number | object): void; - toggleVisibility(node: number | object): void; - updateNodeVisibilityTracking(node: number | object, visible: boolean): void; - } - } - - namespace UI { - class Control { - container: HTMLElement; - - getId(): string; - isCollapsed(): boolean; - setCollapsed(collappsed: boolean): boolean; - setToolTip(toolTipText: string): void; - getToolTip(): string; - isVisible(): boolean; - setVisible(visible: boolean): boolean; - } - - class Button extends Control { - constructor(id: string, options?: any); - - setIcon(iconClass: string): void; - getState(): Button.State; - setState(state: Button.State): boolean; - onClick(event: MouseEvent): void; - onMouseOver(event: MouseEvent): void; - onMouseOut(event: MouseEvent): void; - } - - // NOTE: TypeScript doesn't support enum inside class - namespace Button { - enum State { ACTIVE, INACTIVE, DISABLED } - } - - class ControlGroup extends Control { - constructor(id: string, options?: any); - - addClass(name: string): void; - addControl(control: Control, options?: any): any; - removeControl(control: Control | string): any; - getControl(controlId: string): Control; - getNumberOfControls(): number; - } - - class ToolBar extends ControlGroup { - addEventListener(event: string, callback: () => void): void; - getDimensions(): { width: number, height: number }; - } - - namespace ToolBar { - interface Event { - SIZE_CHANGED: string; - CONTROL_REMOVED: string; - CONTROL_ADDED: string; - COLLAPSED_CHANGED: string; - VISIBILITY_CHANGED: string; - } - } - - interface ClientRect { - bottom: number; - height: number; - left: number; - right: number; - top: number; - width: number; - } - - interface ContentSize { - height: number; - width: number; - } - - class DockingPanel { - constructor(parentContainer: any, id: string, title: string, options?: any); - - closer: HTMLElement; - container: any; - content: any; - id: string; - scrollContainer: HTMLElement; - title: string; - titleTable: string; - - initialize(): void; - uninitialize(): void; - setVisible(show: boolean): void; - isVisible(): boolean; - getContentSize(): ContentSize; - resizeToContent(): void; - getContainerBoundingRect(): ClientRect; - setTitle(text: string, options: any): void; - createCloseButton(): HTMLElement; - createScrollContainer(options: { - heightAdjustment?: number; - left?: boolean; - marginTop?: number; - }): void; - initializeMoveHandlers(mover: HTMLElement): void; - initializeCloseHandler(close: HTMLElement): void; - - visibilityChanged(): void; - onStartMove(event: MouseEvent, startX: number, startY: number): void; - onEndMove(event: MouseEvent, endX: number, endY: number): void; - onMove(event: MouseEvent, currentX: number, currentY: number): void; - onTitleClick(event: Event): void; - onTitleDoubleClick(event: Event): void; - - addVisibilityListener(callback: (state: boolean) => void): void; - - addEventListener(target: object, eventId: string, callback: (event: any) => void): void; - removeEventListener(target: object, eventId: string, callback: (event: any) => void): boolean; - } - } - } -} From fdf388954edab077171456d5467921e70532458e Mon Sep 17 00:00:00 2001 From: Adam Krantz Date: Wed, 23 Jan 2019 07:47:47 -0800 Subject: [PATCH 053/312] Update tests and tweak comments --- .../custom-functions-runtime-tests.ts | 18 +++++---- types/custom-functions-runtime/index.d.ts | 39 ++++++++----------- 2 files changed, 26 insertions(+), 31 deletions(-) diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 2104173734..3b773e95b1 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -10,15 +10,18 @@ CustomFunctions.associate({ RANDOM: (n: number) => n * Math.random() }); +function callerAddress(invocation: CustomFunctions.Invocation) { + return invocation.address; +} + async function getStockValues(ticker: string): Promise { const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())["price"]; } -async function getStockValuesCancellable( - ticker: string, - invocation: CustomFunctions.CancelableInvocation -): Promise { +async function getStockValuesCancellable(ticker: string, + invocation: CustomFunctions.CancelableInvocation): Promise { + const address = invocation.address; let shouldStop = false; invocation.onCanceled = () => (shouldStop = true); await pause(1000); @@ -31,10 +34,9 @@ async function getStockValuesCancellable( return (await response.json())["price"]; } -function stockPriceStream( - ticker: string, - invocation: CustomFunctions.StreamingInvocation -) { +function stockPriceStream(ticker: string, + invocation: CustomFunctions.StreamingInvocation) { + const address = invocation.address; const updateFrequency = 10 /* milliseconds*/; let isPending = false; diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index b2616dcf11..7347a646e8 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -13,89 +13,82 @@ Copyright (c) Microsoft Corporation */ /** - * CustomFunctions namespace, used by Excel Custom Functions * @beta + * CustomFunctions namespace, used by Excel Custom Functions */ declare namespace CustomFunctions { /** - * Associates the JavaScript function to the name given by the "id" property in the metadata JSON file. * @beta + * Associates the JavaScript function to the name given by the "id" property in the metadata JSON file. */ function associate(id: string, functionObject: Function): void; /** - * Associates the JavaScript functions to the names given by the "id" properties in the metadata JSON file. * @beta + * Associates the JavaScript functions to the names given by the "id" properties in the metadata JSON file. */ function associate(mappings: { [key: string]: Function }): void; /** - * Provides information about the invocation of a custom function. * @beta + * Provides information about the invocation of a custom function. */ interface Invocation { /** + * @beta * The cell address where the function is being called, if requested, otherwise undefined. * * To request the address for the function, in the metadata JSON file, the function options should specify: + * `{ "requiresAddress": true }` * - * { - * "requiresAddress": true - * } - * - * If the metadata JSON file is being generated from JSDoc comments, include the tag "@requiresAddress". + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@requiresAddress`. */ address?: string; } /** + * @beta * Provides information about the invocation of a cancelable custom function. * A cancelable custom function can provide a handler for the onCanceled event. - * @beta * * To indicate that a function is cancelable, in the metadata JSON file, the function options should specify: + * `{ "cancelable": true }` * - * { - * "cancelable": true - * } - * - * If the metadata JSON file is being generated from JSDoc comments, include the tag "@cancelable". + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@cancelable`. */ interface CancelableInvocation extends Invocation { /** - * Event handler called when the custom function is canceled. * @beta + * Event handler called when the custom function is canceled. */ onCanceled: () => void; } /** - * Provides information about the invocation of a cancelable custom function. * @beta - * @deprecated Use CancelableInvocation instead. + * @deprecated Use `CancelableInvocation` instead. */ interface CancelableHandler extends CancelableInvocation { } /** + * @beta * Provides information about the invocation of a streaming custom function. * A streaming custom function can provide results which can change over time. * - * Call setResult() one or more times to provide the result instead of returning + * Call `setResult()` one or more times to provide the result instead of returning * a result from the function. - * @beta */ interface StreamingInvocation extends CancelableInvocation { /** - * Sets the result for the custom function. May be called more than once. * @beta + * Set the result for the custom function. May be called more than once. */ setResult: (value: ResultType | Error) => void; } /** - * Provides information about the invocation of a streaming custom function. * @beta - * @deprecated Use StreamingInvocation instead. + * @deprecated Use `StreamingInvocation` instead. */ interface StreamingHandler extends StreamingInvocation { } From 1dd9ab2c99253f0938b9223e32bec16e9a52b72c Mon Sep 17 00:00:00 2001 From: Adam Krantz Date: Wed, 23 Jan 2019 08:46:20 -0800 Subject: [PATCH 054/312] fix tslint errors --- types/custom-functions-runtime/index.d.ts | 16 ++++++++-------- types/custom-functions-runtime/tslint.json | 3 ++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index 7347a646e8..c907fe327e 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for Custom Functions 1.4 // Project: https://github.com/OfficeDev/office-js -// Definitions by: OfficeDev , +// Definitions by: OfficeDev , // Adam Krantz , -// Michael Zlatkovsky , +// Michael Zlatkovsky , // Michelle Scharlock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -36,10 +36,10 @@ declare namespace CustomFunctions { /** * @beta * The cell address where the function is being called, if requested, otherwise undefined. - * + * * To request the address for the function, in the metadata JSON file, the function options should specify: * `{ "requiresAddress": true }` - * + * * If the metadata JSON file is being generated from JSDoc comments, include the tag `@requiresAddress`. */ address?: string; @@ -49,10 +49,10 @@ declare namespace CustomFunctions { * @beta * Provides information about the invocation of a cancelable custom function. * A cancelable custom function can provide a handler for the onCanceled event. - * + * * To indicate that a function is cancelable, in the metadata JSON file, the function options should specify: * `{ "cancelable": true }` - * + * * If the metadata JSON file is being generated from JSDoc comments, include the tag `@cancelable`. */ interface CancelableInvocation extends Invocation { @@ -67,14 +67,14 @@ declare namespace CustomFunctions { * @beta * @deprecated Use `CancelableInvocation` instead. */ - interface CancelableHandler extends CancelableInvocation { + interface CancelableHandler extends CancelableInvocation { } /** * @beta * Provides information about the invocation of a streaming custom function. * A streaming custom function can provide results which can change over time. - * + * * Call `setResult()` one or more times to provide the result instead of returning * a result from the function. */ diff --git a/types/custom-functions-runtime/tslint.json b/types/custom-functions-runtime/tslint.json index ad17c76132..bb858f4682 100644 --- a/types/custom-functions-runtime/tslint.json +++ b/types/custom-functions-runtime/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "file-name-casing": false + "file-name-casing": false, + "no-empty-interface": false } } From 353ca607b47960fa772ab68463961993a95bac6d Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 23 Jan 2019 17:11:49 +0100 Subject: [PATCH 055/312] Handle ComponentType --- types/enzyme/index.d.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 0818b4e5ce..58e5938a8f 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -27,7 +27,9 @@ export interface ComponentClass { new(props: Props, context?: any): Component; } -export type StatelessComponent = (props: Props, context?: any) => JSX.Element; +export type StatelessComponent = (props: Props, context?: any) => JSX.Element | null; + +export type ComponentType = ComponentClass | StatelessComponent; /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the @@ -372,8 +374,8 @@ export class ShallowWrapper

    { * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ShallowWrapper; find(statelessComponent: StatelessComponent): ShallowWrapper; + find(component: ComponentType): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -381,8 +383,8 @@ export class ShallowWrapper

    { * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(component: ComponentType): ShallowWrapper; filter(props: EnzymePropSelector | string): ShallowWrapper; /** @@ -394,8 +396,8 @@ export class ShallowWrapper

    { * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; + children(component: ComponentType): ShallowWrapper; children(selector: string): ShallowWrapper; children(props?: EnzymePropSelector): ShallowWrapper; @@ -425,8 +427,8 @@ export class ShallowWrapper

    { * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(component: ComponentType): ShallowWrapper; parents(selector: string): ShallowWrapper; parents(props?: EnzymePropSelector): ShallowWrapper; @@ -436,8 +438,8 @@ export class ShallowWrapper

    { * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(component: ComponentType): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -487,8 +489,8 @@ export class ReactWrapper

    { * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ReactWrapper; find(statelessComponent: StatelessComponent): ReactWrapper; + find(component: ComponentType): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -501,16 +503,16 @@ export class ReactWrapper

    { * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ReactWrapper; filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(component: ComponentType): ReactWrapper; filter(props: EnzymePropSelector | string): ReactWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ReactWrapper; children(statelessComponent: StatelessComponent): ReactWrapper; + children(component: ComponentType): ReactWrapper; children(selector: string): ReactWrapper; children(props?: EnzymePropSelector): ReactWrapper; @@ -526,8 +528,8 @@ export class ReactWrapper

    { * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ReactWrapper; parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(component: ComponentType): ReactWrapper; parents(selector: string): ReactWrapper; parents(props?: EnzymePropSelector): ReactWrapper; @@ -537,8 +539,8 @@ export class ReactWrapper

    { * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ReactWrapper; closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(component: ComponentType): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; From acf3abcb1ce933160f6a785a8a95438822257dca Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 01:51:44 +0700 Subject: [PATCH 056/312] Add ChangeEvent interface supporting rawValue property on target --- types/cleave.js/index.d.ts | 1 + types/cleave.js/react/index.d.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 77d2e818ca..12c332249b 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: C Lentfort , // J Giancono , // Alex Shakun +// Hiep Le // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/cleave.js/react/index.d.ts b/types/cleave.js/react/index.d.ts index bf158b8f4d..0459221f2a 100644 --- a/types/cleave.js/react/index.d.ts +++ b/types/cleave.js/react/index.d.ts @@ -2,4 +2,9 @@ import * as React from "react"; import { Props } from "./props"; declare var Cleave: React.ComponentClass; +declare namespace Cleave { + interface ChangeEvent extends React.ChangeEvent { + target: { rawValue: string } & EventTarget & T + } +} export = Cleave; From 06fe463d62fbf6c7b2b91e7a90fa1159a9e58306 Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 02:11:00 +0700 Subject: [PATCH 057/312] Remove my name since it is not needed --- types/cleave.js/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 12c332249b..77d2e818ca 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: C Lentfort , // J Giancono , // Alex Shakun -// Hiep Le // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 From 56f74c493b24977ae52c9585ddfc19095e84619e Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 02:11:13 +0700 Subject: [PATCH 058/312] Bump version of cleave.js --- types/cleave.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 77d2e818ca..91a9af1b17 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cleave.js 1.3 +// Type definitions for cleave.js 1.4.7 // Project: https://github.com/nosir/cleave.js // Definitions by: C Lentfort , // J Giancono , From 0d3bb83141c45ca5ae7cd77d8308e56ea53a044a Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 02:35:06 +0700 Subject: [PATCH 059/312] Add test and move ChangeEvent interface --- types/cleave.js/cleave.js-tests.tsx | 16 +++++++++++++++- types/cleave.js/react/index.d.ts | 5 ----- types/cleave.js/react/props.d.ts | 7 +++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/types/cleave.js/cleave.js-tests.tsx b/types/cleave.js/cleave.js-tests.tsx index a826d2607a..461e4f4d05 100644 --- a/types/cleave.js/cleave.js-tests.tsx +++ b/types/cleave.js/cleave.js-tests.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import Cleave = require("cleave.js"); import CleaveReact = require("cleave.js/react"); -import { Props } from "cleave.js/react/props"; +import { Props, ChangeEvent } from "cleave.js/react/props"; const ExampleSelector1 = () => { const cleave = new Cleave("#my-input", { phone: true }); @@ -41,3 +41,17 @@ const ExampleReact2 = (props: Props) => { /> ); }; + +const ExampleReact3 = (props: Props) => { + const handleChange = (e: ChangeEvent) => { + return e.target.rawValue; + }; + return ( + + ); +}; diff --git a/types/cleave.js/react/index.d.ts b/types/cleave.js/react/index.d.ts index 0459221f2a..bf158b8f4d 100644 --- a/types/cleave.js/react/index.d.ts +++ b/types/cleave.js/react/index.d.ts @@ -2,9 +2,4 @@ import * as React from "react"; import { Props } from "./props"; declare var Cleave: React.ComponentClass; -declare namespace Cleave { - interface ChangeEvent extends React.ChangeEvent { - target: { rawValue: string } & EventTarget & T - } -} export = Cleave; diff --git a/types/cleave.js/react/props.d.ts b/types/cleave.js/react/props.d.ts index 6ce47db62c..1e190fb729 100644 --- a/types/cleave.js/react/props.d.ts +++ b/types/cleave.js/react/props.d.ts @@ -3,8 +3,15 @@ import { CleaveOptions } from "../options"; export type InitHandler = (owner: React.ReactInstance) => void; +export interface ChangeEvent extends React.ChangeEvent { + target: { rawValue: string } & EventTarget & T +} + +export type ChangeEventHandler = React.EventHandler>; + export interface Props extends React.InputHTMLAttributes { onInit?: InitHandler; options: CleaveOptions; htmlRef?: (i: any) => void; + onChange?: ChangeEventHandler } From ccc4e0ce4523a639cd0151f1a8d6d89e702aff49 Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 02:52:13 +0700 Subject: [PATCH 060/312] Add semicolon --- types/cleave.js/react/props.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/cleave.js/react/props.d.ts b/types/cleave.js/react/props.d.ts index 1e190fb729..d881e1b319 100644 --- a/types/cleave.js/react/props.d.ts +++ b/types/cleave.js/react/props.d.ts @@ -4,7 +4,7 @@ import { CleaveOptions } from "../options"; export type InitHandler = (owner: React.ReactInstance) => void; export interface ChangeEvent extends React.ChangeEvent { - target: { rawValue: string } & EventTarget & T + target: { rawValue: string } & EventTarget & T; } export type ChangeEventHandler = React.EventHandler>; @@ -13,5 +13,5 @@ export interface Props extends React.InputHTMLAttributes { onInit?: InitHandler; options: CleaveOptions; htmlRef?: (i: any) => void; - onChange?: ChangeEventHandler + onChange?: ChangeEventHandler; } From 09c80891ecdde772bb8beaff2858815b57e696c5 Mon Sep 17 00:00:00 2001 From: Hiep Le Date: Thu, 24 Jan 2019 02:59:49 +0700 Subject: [PATCH 061/312] Fix version --- types/cleave.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 91a9af1b17..11067195ea 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cleave.js 1.4.7 +// Type definitions for cleave.js 1.4 // Project: https://github.com/nosir/cleave.js // Definitions by: C Lentfort , // J Giancono , From 4aa9fbc68f5d0946086c0bb8d53219b7df17a1a2 Mon Sep 17 00:00:00 2001 From: Jeong Woo Chang Date: Wed, 23 Jan 2019 15:31:21 -0800 Subject: [PATCH 062/312] wrongly typed callbacks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As official demo code shows that the callbacks are wrongly typed. ``` // Callbacks usage example var clusterize = new Clusterize({ … callbacks: { clusterWillChange: function() {}, clusterChanged: function() {}, scrollingProgress: function(progress) {} } }); ``` --- types/clusterize.js/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index 7c549761d6..47da5a2140 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -32,9 +32,9 @@ declare namespace Clusterize { } interface Callbacks { - clusterWillChange?(cb: () => void): void; - clusterChanged?(cb: () => void): void; - scrollingProgress?(cb: (progress: number) => void): void; + clusterWillChange?: () => void; + clusterChanged?: () => void; + scrollingProgress?: (progress: number) => void; } } From 867ce620d4e0283ffb632431fb49ed5e0582e88f Mon Sep 17 00:00:00 2001 From: Alex Brick Date: Thu, 24 Jan 2019 15:58:41 +0100 Subject: [PATCH 063/312] [btoa] Exporting the function in the legacy style This definition was incorrectly declaring the function as a default export, as opposed to a legacy-style on the exports directly. Closes #28648 --- types/btoa/btoa-tests.ts | 2 +- types/btoa/index.d.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/btoa/btoa-tests.ts b/types/btoa/btoa-tests.ts index d09cdad23a..7ce230fcf7 100644 --- a/types/btoa/btoa-tests.ts +++ b/types/btoa/btoa-tests.ts @@ -1,3 +1,3 @@ -import btoa from 'btoa'; +import btoa = require('btoa'); btoa('foo'); diff --git a/types/btoa/index.d.ts b/types/btoa/index.d.ts index cc311ed836..bdb02b5b59 100644 --- a/types/btoa/index.d.ts +++ b/types/btoa/index.d.ts @@ -1,7 +1,10 @@ // Type definitions for btoa 1.2 // Project: https://git.coolaj86.com/coolaj86/btoa.js // Definitions by: John Wright +// Alex Brick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -export default function(str: string): string; +declare function btoa(str: string): string; + +export = btoa; From 607aff8f56075c9540c805d17569eaec9d478de0 Mon Sep 17 00:00:00 2001 From: Pierre Krafft Date: Thu, 24 Jan 2019 18:41:07 +0100 Subject: [PATCH 064/312] Update p5 to 0.7.3 --- types/p5/constants.d.ts | 10 +- types/p5/global.d.ts | 312 ++++++++++++++---- types/p5/index.d.ts | 3 +- types/p5/lib/addons/p5.dom.d.ts | 39 +++ types/p5/lib/addons/p5.sound.d.ts | 27 +- types/p5/literals.d.ts | 2 + types/p5/src/color/setting.d.ts | 12 +- types/p5/src/core/constants.d.ts | 1 + types/p5/src/core/environment.d.ts | 12 +- types/p5/src/core/p5.Element.d.ts | 51 +-- types/p5/src/core/shape/2d_primitives.d.ts | 67 +++- types/p5/src/events/acceleration.d.ts | 13 +- types/p5/src/events/keyboard.d.ts | 12 +- types/p5/src/image/p5.Image.d.ts | 10 +- types/p5/src/image/pixels.d.ts | 20 +- types/p5/src/io/files.d.ts | 16 +- types/p5/src/io/p5.XML.d.ts | 8 + types/p5/src/math/calculation.d.ts | 13 +- types/p5/src/typography/attributes.d.ts | 18 +- .../p5/src/typography/loading_displaying.d.ts | 2 +- types/p5/src/typography/p5.Font.d.ts | 3 + types/p5/src/utilities/string_functions.d.ts | 70 +++- types/p5/src/webgl/material.d.ts | 17 + 23 files changed, 554 insertions(+), 184 deletions(-) diff --git a/types/p5/constants.d.ts b/types/p5/constants.d.ts index 808e55b72e..df2bc6d3c7 100644 --- a/types/p5/constants.d.ts +++ b/types/p5/constants.d.ts @@ -46,8 +46,7 @@ declare module "./index" { | CROSS | HAND | MOVE - | TEXT - | WAIT; + | TEXT; type DEBUG_MODE = | GRID @@ -110,10 +109,15 @@ declare module "./index" { | BEVEL | ROUND; + type TEXTURE_MODE = + | IMAGE + | NORMAL; + type THE_STYLE = | NORMAL | ITALIC - | BOLD; + | BOLD + | BOLDITALIC; type TYPE = | VIDEO diff --git a/types/p5/global.d.ts b/types/p5/global.d.ts index 6dd593e282..13bcd8acc4 100644 --- a/types/p5/global.d.ts +++ b/types/p5/global.d.ts @@ -307,7 +307,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -344,7 +344,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -385,7 +385,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -425,7 +425,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -471,7 +471,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -508,7 +508,7 @@ declare global { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -969,6 +969,7 @@ declare global { * @param w width of the ellipse. * @param h height of the ellipse. * @param detail number of radial sectors to draw + * (for WebGL mode) */ function ellipse( x: number, @@ -978,6 +979,28 @@ declare global { detail: number ): void; + /** + * Draws a circle to the screen. A circle is a simple + * closed shape. It is the set of all points in a + * plane that are at a given distance from a given + * point, the centre. This function is a special case + * of the ellipse() function, where the width and + * height of the ellipse are the same. Height and + * width of the ellipse is equal to twice the radius + * of the circle.. By default, the first two + * parameters set the location of the centre of the + * circle, the third sets the radius of the circle. + * @param x x-coordinate of the centre of the circle. + * @param y y-coordinate of the centre of the circle. + * @param r radius of the circle. + * @chainable + */ + function circle( + x: number, + y: number, + r: number + ): p5; + /** * Draws a line (a direct path between two points) to * the screen. The version of line() with four @@ -1034,7 +1057,7 @@ declare global { * the point is determined by the current stroke. * @param x the x-coordinate * @param y the y-coordinate - * @param [z] the z-coordinate (for WEBGL mode) + * @param [z] the z-coordinate (for WebGL mode) * @chainable */ function point( @@ -1164,9 +1187,9 @@ declare global { * @param w width of the rectangle. * @param h height of the rectangle. * @param [detailX] number of segments in the - * x-direction + * x-direction (for WebGL mode) * @param [detailY] number of segments in the - * y-direction + * y-direction (for WebGL mode) * @chainable */ function rect( @@ -1178,6 +1201,44 @@ declare global { detailY?: number ): p5; + /** + * Draws a square to the screen. A square is a + * four-sided shape with every angle at ninety + * degrees, and equal side size. This function is a + * special case of the rect() function, where the + * width and height are the same, and the parameter + * is called "s" for side size. By default, the first + * two parameters set the location of the upper-left + * corner, the third sets the side size of the + * square. The way these parameters are interpreted, + * however, may be changed with the rectMode() + * function. The fourth, fifth, sixth and seventh + * parameters, if specified, determine corner radius + * for the top-left, top-right, lower-right and + * lower-left corners, respectively. An omitted + * corner radius parameter is set to the value of the + * previously specified radius value in the parameter + * list. + * @param x x-coordinate of the square. + * @param y y-coordinate of the square. + * @param s side size of the square. + * @param [tl] optional radius of top-left corner. + * @param [tr] optional radius of top-right corner. + * @param [br] optional radius of bottom-right + * corner. + * @param [bl] optional radius of bottom-left corner. + * @chainable + */ + function square( + x: number, + y: number, + s: number, + tl?: number, + tr?: number, + br?: number, + bl?: number + ): p5; + /** * A triangle is a plane created by connecting three * points. The first two arguments specify the first @@ -2085,6 +2146,7 @@ declare global { const NORMAL: p5.NORMAL; const ITALIC: p5.ITALIC; const BOLD: p5.BOLD; + const BOLDITALIC: p5.BOLDITALIC; const LANDSCAPE: p5.LANDSCAPE; const PORTRAIT: p5.PORTRAIT; const GRID: p5.GRID; @@ -2116,11 +2178,17 @@ declare global { * recommended size is 16x16 or 32x32 pixels. The * values for parameters x and y must be less than * the dimensions of the image. - * @param type either ARROW, CROSS, HAND, MOVE, TEXT, - * or WAIT, or path for image + * @param type Built-In: either ARROW, CROSS, HAND, + * MOVE, TEXT and WAIT Native CSS properties: 'grab', + * 'progress', 'cell' etc. External: path for + * cursor's images (Allowed File extensions: .cur, + * .gif, .jpg, .jpeg, .png) For more information on + * Native CSS cursors and url visit: + * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor * @param [x] the horizontal active spot of the - * cursor + * cursor (must be less than 32) * @param [y] the vertical active spot of the cursor + * (must be less than 32) */ function cursor( type: @@ -2872,7 +2940,8 @@ declare global { * The deviceMoved() function is called when the * device is moved by more than the threshold value * along X, Y or Z axis. The default threshold is set - * to 0.5. + * to 0.5. The threshold value can be changed using + * setMoveThreshold(). */ function deviceMoved(): void; @@ -2892,7 +2961,8 @@ declare global { * device total acceleration changes of accelerationX * and accelerationY values is more than the * threshold value. The default threshold is set to - * 30. + * 30. The threshold value can be changed using + * setShakeThreshold(). */ function deviceShaken(): void; @@ -3014,6 +3084,13 @@ declare global { * rotate direction of the device along the Z-axis. */ let pRotationZ: number; + + /** + * When a device is rotated, the axis that triggers + * the deviceTurned() method is stored in the + * turnAxis variable. The turnAxis variable is only + * defined within the scope of deviceTurned(). + */ let turnAxis: string; /** @@ -3027,12 +3104,12 @@ declare global { * LEFT_ARROW, RIGHT_ARROW. * * - * For ASCII keys that was pressed is stored in the - * key variable. However, it does not distinguish - * between uppercase and lowercase. For this reason, - * it is recommended to use keyTyped() to read the - * key variable, in which the case of the variable - * will be distinguished. + * For ASCII keys, the key that was pressed is stored + * in the key variable. However, it does not + * distinguish between uppercase and lowercase. For + * this reason, it is recommended to use keyTyped() + * to read the key variable, in which the case of the + * variable will be distinguished. * * * Because of how operating systems handle key @@ -3984,12 +4061,16 @@ declare global { * is easy, but not as fast as grabbing the data * directly from pixels[]. The equivalent statement * to get(x, y) using pixels[] with pixel density d - * is var x, y, d; // set these to the coordinates - * var off = (y width + x) d * 4; var components = - * [ pixels[off], pixels[off + 1], pixels[off + 2], + * is + * + * let x, y, d; // set these to the coordinates let + * off = (y * width + x) * d * 4; let components = [ + * pixels[off], pixels[off + 1], pixels[off + 2], * pixels[off + 3] ]; print(components); * * + * + * * See the reference for pixels[] for more * information. * @@ -4105,11 +4186,11 @@ declare global { * pixel at (1, 0). More generally, to set values for * a pixel at (x, y): * - * var d = pixelDensity(); for (var i = 0; i < d; - * i++) { for (var j = 0; j < d; j++) { // loop over - * idx = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[idx] = r; pixels[idx+1] = g; pixels[idx+2] - * = b; pixels[idx+3] = a; } } + * let d = pixelDensity(); for (let i = 0; i < d; + * i++) { for (let j = 0; j < d; j++) { // loop over + * index = 4 * ((y * d + j) * width * d + (x * d + + * i)); pixels[index] = r; pixels[index+1] = g; + * pixels[index+2] = b; pixels[index+3] = a; } } * * While the above method is complex, it is flexible * enough to work with any pixelDensity. Note that @@ -4294,6 +4375,8 @@ declare global { * - tsv - parse the table as tab-separated values * - header - this table has a header (title) row * + * + * * When passing in multiple options, pass them in as * separate parameters, seperated by commas. For * example: @@ -4352,6 +4435,8 @@ declare global { * - tsv - parse the table as tab-separated values * - header - this table has a header (title) row * + * + * * When passing in multiple options, pass them in as * separate parameters, seperated by commas. For * example: @@ -4749,22 +4834,22 @@ declare global { * * * // Saves canvas as an image save('myCanvas.jpg'); - * // Saves pImage as a png image var img = + * // Saves pImage as a png image let img = * createImage(10, 10); save(img, 'my.png'); // Saves - * canvas as an image var cnv = createCanvas(100, + * canvas as an image let cnv = createCanvas(100, * 100); save(cnv, 'myCanvas.jpg'); // Saves - * p5.Renderer object as an image var gb = + * p5.Renderer object as an image let gb = * createGraphics(100, 100); save(gb, - * 'myGraphics.jpg'); var myTable = new p5.Table(); + * 'myGraphics.jpg'); let myTable = new p5.Table(); * // Saves table as html file save(myTable, * 'myTable.html'); // Comma Separated Values * save(myTable, 'myTable.csv'); // Tab Separated - * Values save(myTable, 'myTable.tsv'); var myJSON = + * Values save(myTable, 'myTable.tsv'); let myJSON = * { a: 1, b: true }; // Saves pretty JSON * save(myJSON, 'my.json'); // Optimizes JSON * filesize save(myJSON, 'my.json', true); // Saves * array of strings to a text file with line breaks - * after each item var arrayOfStrings = ['a', 'b']; + * after each item let arrayOfStrings = ['a', 'b']; * save(arrayOfStrings, 'my.txt'); * @param [objectOrFilename] If filename is provided, * will save canvas as an image with either png or @@ -4938,13 +5023,16 @@ declare global { * specific increment. The amt parameter is the * amount to interpolate between the two values where * 0.0 equal to the first point, 0.1 is very near the - * first point, 0.5 is half-way in between, etc. The - * lerp function is convenient for creating motion - * along a straight path and for drawing dotted - * lines. + * first point, 0.5 is half-way in between, and 1.0 + * is equal to the second point. If the value of amt + * is more than 1.0 or less than 0.0, the number will + * be calculated accordingly in the ratio of the two + * given numbers. The lerp function is convenient for + * creating motion along a straight path and for + * drawing dotted lines. * @param start first value * @param stop second value - * @param amt number between 0.0 and 1.0 + * @param amt number * @return lerped value */ function lerp( @@ -5549,12 +5637,12 @@ declare global { /** * Sets/gets the style of the text for system fonts - * to NORMAL, ITALIC, or BOLD. Note: this may be is - * overridden by CSS styling. For non-system fonts - * (opentype, truetype, etc.) please load styled - * fonts instead. + * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this + * may be is overridden by CSS styling. For + * non-system fonts (opentype, truetype, etc.) please + * load styled fonts instead. * @param theStyle styling for text, either NORMAL, - * ITALIC, or BOLD + * ITALIC, BOLD or BOLDITALIC * @chainable */ function textStyle( @@ -5563,10 +5651,10 @@ declare global { /** * Sets/gets the style of the text for system fonts - * to NORMAL, ITALIC, or BOLD. Note: this may be is - * overridden by CSS styling. For non-system fonts - * (opentype, truetype, etc.) please load styled - * fonts instead. + * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this + * may be is overridden by CSS styling. For + * non-system fonts (opentype, truetype, etc.) please + * load styled fonts instead. */ function textStyle(): string; @@ -5601,7 +5689,7 @@ declare global { * method is asynchronous, meaning it may not finish * before the next line in your sketch is executed. * The path to the font should be relative to the - * HTML file that links in your sketch. Loading an + * HTML file that links in your sketch. Loading fonts * from a URL or other remote location may be blocked * due to your browser's built-in security. * @param path name of the file or url to load @@ -6207,6 +6295,14 @@ declare global { * formatting floats, and one for formatting ints. * The values for the digits, left, and right * parameters should always be positive integers. + * (NOTE): Be cautious when using left and right + * parameters as it prepends numbers of 0's if the + * parameter if greater than the current length of + * the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param num the Number to format * @param [left] number of digits to the left of the * decimal point @@ -6232,6 +6328,14 @@ declare global { * formatting floats, and one for formatting ints. * The values for the digits, left, and right * parameters should always be positive integers. + * (NOTE): Be cautious when using left and right + * parameters as it prepends numbers of 0's if the + * parameter if greater than the current length of + * the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param nums the Numbers to format * @param [left] number of digits to the left of the * decimal point @@ -6333,12 +6437,27 @@ declare global { /** * Utility function for formatting numbers into - * strings. Similar to nf() but puts a " " (space) in - * front of positive numbers and a "-" in front of - * negative numbers. There are two versions: one for - * formatting floats, and one for formatting ints. - * The values for the digits, left, and right - * parameters should always be positive integers. + * strings. Similar to nf() but puts an additional + * "_" (space) in front of positive numbers just in + * case to align it with negative numbers which + * includes "-" (minus) sign. The main usecase of + * nfs() can be seen when one wants to align the + * digits (place values) of a positive number with + * some negative number (See the example to get a + * clear picture). There are two versions: one for + * formatting float, and one for formatting int. The + * values for the digits, left, and right parameters + * should always be positive integers. (IMP): The + * result on the canvas basically the expected + * alignment can vary based on the typeface you are + * using. (NOTE): Be cautious when using left and + * right parameters as it prepends numbers of 0's if + * the parameter if greater than the current length + * of the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param num the Number to format * @param [left] number of digits to the left of the * decimal point @@ -6354,12 +6473,27 @@ declare global { /** * Utility function for formatting numbers into - * strings. Similar to nf() but puts a " " (space) in - * front of positive numbers and a "-" in front of - * negative numbers. There are two versions: one for - * formatting floats, and one for formatting ints. - * The values for the digits, left, and right - * parameters should always be positive integers. + * strings. Similar to nf() but puts an additional + * "_" (space) in front of positive numbers just in + * case to align it with negative numbers which + * includes "-" (minus) sign. The main usecase of + * nfs() can be seen when one wants to align the + * digits (place values) of a positive number with + * some negative number (See the example to get a + * clear picture). There are two versions: one for + * formatting float, and one for formatting int. The + * values for the digits, left, and right parameters + * should always be positive integers. (IMP): The + * result on the canvas basically the expected + * alignment can vary based on the typeface you are + * using. (NOTE): Be cautious when using left and + * right parameters as it prepends numbers of 0's if + * the parameter if greater than the current length + * of the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param nums the Numbers to format * @param [left] number of digits to the left of the * decimal point @@ -7158,6 +7292,23 @@ declare global { | p5.Graphics ): p5; + /** + * Sets the coordinate space for texture mapping. The + * default mode is IMAGE which refers to the actual + * coordinates of the image. NORMAL refers to a + * normalized space of values ranging from 0 to 1. + * This function only works in WEBGL mode. With + * IMAGE, if an image is 100 x 200 pixels, mapping + * the image onto the entire size of a quad would + * require the points (0,0) (100, 0) (100,200) + * (0,200). The same mapping in NORMAL is (0,0) (1,0) + * (1,1) (0,1). + * @param mode either IMAGE or NORMAL + */ + function textureMode( + mode: p5.TEXTURE_MODE + ): void; + /** * Ambient material for geometry with a given color. * You can view all possible materials in this @@ -7477,6 +7628,45 @@ declare global { */ function removeElements(): void; + /** + * The .changed() function is called when the value + * of an element changes. This can be used to attach + * an element specific event listener. + * @param fxn function to be fired when the value of + * an element changes. if false is passed instead, + * the previously firing function will no longer + * fire. + * @chainable + */ + function changed( + fxn: + | (( + ...args: any[] + ) => any) + | boolean + ): p5; + + /** + * The .input() function is called when any user + * input is detected with an element. The input event + * is often used to detect keystrokes in a input + * element, or changes on a slider element. This can + * be used to attach an element specific event + * listener. + * @param fxn function to be fired when any user + * input is detected within the element. if false is + * passed instead, the previously firing function + * will no longer fire. + * @chainable + */ + function input( + fxn: + | (( + ...args: any[] + ) => any) + | boolean + ): p5; + /** * Creates a

    element in the DOM with * given inner HTML. Appends to the container node if diff --git a/types/p5/index.d.ts b/types/p5/index.d.ts index f87978d993..47ec26df31 100644 --- a/types/p5/index.d.ts +++ b/types/p5/index.d.ts @@ -2,10 +2,11 @@ // Project: https://github.com/processing/p5.js // Definitions by: p5-types // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.9 // This file was auto-generated. Please do not edit it. +/// /// /// /// diff --git a/types/p5/lib/addons/p5.dom.d.ts b/types/p5/lib/addons/p5.dom.d.ts index 7a4f2e096b..8566cf1cf3 100644 --- a/types/p5/lib/addons/p5.dom.d.ts +++ b/types/p5/lib/addons/p5.dom.d.ts @@ -336,6 +336,45 @@ declare module "../../index" { */ removeElements(): void; + /** + * The .changed() function is called when the value + * of an element changes. This can be used to attach + * an element specific event listener. + * @param fxn function to be fired when the value of + * an element changes. if false is passed instead, + * the previously firing function will no longer + * fire. + * @chainable + */ + changed( + fxn: + | (( + ...args: any[] + ) => any) + | boolean + ): p5; + + /** + * The .input() function is called when any user + * input is detected with an element. The input event + * is often used to detect keystrokes in a input + * element, or changes on a slider element. This can + * be used to attach an element specific event + * listener. + * @param fxn function to be fired when any user + * input is detected within the element. if false is + * passed instead, the previously firing function + * will no longer fire. + * @chainable + */ + input( + fxn: + | (( + ...args: any[] + ) => any) + | boolean + ): p5; + /** * Creates a
    element in the DOM with * given inner HTML. Appends to the container node if diff --git a/types/p5/lib/addons/p5.sound.d.ts b/types/p5/lib/addons/p5.sound.d.ts index faa16f7e1b..b6eb3c5e87 100644 --- a/types/p5/lib/addons/p5.sound.d.ts +++ b/types/p5/lib/addons/p5.sound.d.ts @@ -1990,7 +1990,7 @@ declare module "../../index" { * Reverb adds depth to a sound through a large * number of decaying echoes. It creates the * perception that sound is occurring in a physical - * space. The p5.Reverb has parameters for Time (how + * space. The p5.Reverb has paramters for Time (how * long does the reverb last) and decayRate (how much * the sound decays with each echo) that can be set * with the .set() or .process() methods. The @@ -2270,12 +2270,13 @@ declare module "../../index" { /** * A p5.Part plays back one or more p5.Phrases. * Instantiate a part with steps and tatums. By - * default, each step represents 1/16th note. See + * default, each step represents a 1/16th note. See * p5.Phrase for more about musical timing. * * @param [steps] Steps in the part - * @param [tatums] Divisions of a beat (default is - * 1/16, a quarter note) + * @param [tatums] Divisions of a beat, e.g. use 1/4, + * or 0.25 for a quater note (default is 1/16, a + * sixteenth note) */ constructor( steps?: number, @@ -2293,7 +2294,7 @@ declare module "../../index" { ): void; /** - * Returns the Beats Per Minute of this currently + * Returns the tempo, in Beats Per Minute, of this * part. */ getBPM(): number; @@ -2324,7 +2325,9 @@ declare module "../../index" { noLoop(): void; /** - * Stop the part and cue it to step 0. + * Stop the part and cue it to step 0. Playback will + * resume from the begining of the Part when it is + * played again. * @param [time] seconds from now */ stop( @@ -2366,9 +2369,8 @@ declare module "../../index" { ): void; /** - * Get a phrase from this part, based on the name it - * was given when it was created. Now you can modify - * its array. + * Find all sequences with the specified name, and + * replace their patterns with the specified array. * @param sequence Array of values to pass into the * callback at each step of the phrase. */ @@ -2378,7 +2380,8 @@ declare module "../../index" { ): void; /** - * Fire a callback function at every step. + * Set the function that will be called at every + * step. This will clear the previous function. * @param callback The name of the callback you want * to fire on every beat/tatum. */ @@ -2511,7 +2514,7 @@ declare module "../../index" { maxIterations: number; /** - * Getters and Setters, setting any parameter will + * Getters and Setters, setting any paramter will * result in a change in the clock's frequency, that * will be reflected after the next callback beats * per minute (defaults to 60) @@ -2588,7 +2591,7 @@ declare module "../../index" { ): void; /** - * Set the parameters of a compressor. + * Set the paramters of a compressor. * @param attack The amount of time (in seconds) to * reduce the gain by 10dB, default = .003, range 0 - * 1 diff --git a/types/p5/literals.d.ts b/types/p5/literals.d.ts index 0dc8f8b65a..d1e6aed943 100644 --- a/types/p5/literals.d.ts +++ b/types/p5/literals.d.ts @@ -11,6 +11,7 @@ declare module "./index" { type BLEND = "source-over"; type BLUR = "blur"; type BOLD = "bold"; + type BOLDITALIC = "bolditalic"; type BOTTOM = "bottom"; type BURN = "color-burn"; type CENTER = "center"; @@ -32,6 +33,7 @@ declare module "./index" { type HARD_LIGHT = "hard-light"; type HSB = "hsb"; type HSL = "hsl"; + type IMAGE = "image"; type INVERT = "invert"; type ITALIC = "italic"; type LANDSCAPE = "landscape"; diff --git a/types/p5/src/color/setting.d.ts b/types/p5/src/color/setting.d.ts index c02a705a1e..9a9d01fc2c 100644 --- a/types/p5/src/color/setting.d.ts +++ b/types/p5/src/color/setting.d.ts @@ -7,7 +7,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -44,7 +44,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -85,7 +85,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -125,7 +125,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -171,7 +171,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on @@ -208,7 +208,7 @@ declare module "../../index" { /** * The background() function sets the color used for * the background of the p5.js canvas. The default - * background is light gray. This function is + * background is transparent. This function is * typically used within draw() to clear the display * window at the beginning of each frame, but it can * be used inside setup() to set the background on diff --git a/types/p5/src/core/constants.d.ts b/types/p5/src/core/constants.d.ts index 4daaadfca5..6bed1232f5 100644 --- a/types/p5/src/core/constants.d.ts +++ b/types/p5/src/core/constants.d.ts @@ -128,6 +128,7 @@ declare module "../../index" { readonly NORMAL: NORMAL; readonly ITALIC: ITALIC; readonly BOLD: BOLD; + readonly BOLDITALIC: BOLDITALIC; readonly LANDSCAPE: LANDSCAPE; readonly PORTRAIT: PORTRAIT; readonly GRID: GRID; diff --git a/types/p5/src/core/environment.d.ts b/types/p5/src/core/environment.d.ts index e226544030..be0346f244 100644 --- a/types/p5/src/core/environment.d.ts +++ b/types/p5/src/core/environment.d.ts @@ -30,11 +30,17 @@ declare module "../../index" { * recommended size is 16x16 or 32x32 pixels. The * values for parameters x and y must be less than * the dimensions of the image. - * @param type either ARROW, CROSS, HAND, MOVE, TEXT, - * or WAIT, or path for image + * @param type Built-In: either ARROW, CROSS, HAND, + * MOVE, TEXT and WAIT Native CSS properties: 'grab', + * 'progress', 'cell' etc. External: path for + * cursor's images (Allowed File extensions: .cur, + * .gif, .jpg, .jpeg, .png) For more information on + * Native CSS cursors and url visit: + * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor * @param [x] the horizontal active spot of the - * cursor + * cursor (must be less than 32) * @param [y] the vertical active spot of the cursor + * (must be less than 32) */ cursor( type: diff --git a/types/p5/src/core/p5.Element.d.ts b/types/p5/src/core/p5.Element.d.ts index dbd32afdb6..43fda2ced9 100644 --- a/types/p5/src/core/p5.Element.d.ts +++ b/types/p5/src/core/p5.Element.d.ts @@ -10,7 +10,11 @@ declare module "../../index" { * Accepts either a string ID, DOM node, or * p5.Element. If no arguments given, parent node is * returned. For more ways to position the canvas, - * see the positioning the canvas wiki page. + * see the positioning the canvas wiki page. All + * above examples except for the first one require + * the inclusion of the p5.dom library in your + * index.html. See the using a library section for + * information on how to include this library. * @param parent the ID, DOM node, or p5.Element of * desired parent element * @chainable @@ -28,7 +32,11 @@ declare module "../../index" { * Accepts either a string ID, DOM node, or * p5.Element. If no arguments given, parent node is * returned. For more ways to position the canvas, - * see the positioning the canvas wiki page. + * see the positioning the canvas wiki page. All + * above examples except for the first one require + * the inclusion of the p5.dom library in your + * index.html. See the using a library section for + * information on how to include this library. */ parent(): Element; @@ -218,45 +226,6 @@ declare module "../../index" { | boolean ): Element; - /** - * The .changed() function is called when the value - * of an element changes. This can be used to attach - * an element specific event listener. - * @param fxn function to be fired when the value of - * an element changes. if false is passed instead, - * the previously firing function will no longer - * fire. - * @chainable - */ - changed( - fxn: - | (( - ...args: any[] - ) => any) - | boolean - ): Element; - - /** - * The .input() function is called when any user - * input is detected with an element. The input event - * is often used to detect keystrokes in a input - * element, or changes on a slider element. This can - * be used to attach an element specific event - * listener. - * @param fxn function to be fired when any user - * input is detected within the element. if false is - * passed instead, the previously firing function - * will no longer fire. - * @chainable - */ - input( - fxn: - | (( - ...args: any[] - ) => any) - | boolean - ): Element; - /** * The .mouseOut() function is called once after * every time a mouse moves off the element. This can diff --git a/types/p5/src/core/shape/2d_primitives.d.ts b/types/p5/src/core/shape/2d_primitives.d.ts index 4cced6ef5c..aa8ab3c8e9 100644 --- a/types/p5/src/core/shape/2d_primitives.d.ts +++ b/types/p5/src/core/shape/2d_primitives.d.ts @@ -84,6 +84,7 @@ declare module "../../../index" { * @param w width of the ellipse. * @param h height of the ellipse. * @param detail number of radial sectors to draw + * (for WebGL mode) */ ellipse( x: number, @@ -93,6 +94,28 @@ declare module "../../../index" { detail: number ): void; + /** + * Draws a circle to the screen. A circle is a simple + * closed shape. It is the set of all points in a + * plane that are at a given distance from a given + * point, the centre. This function is a special case + * of the ellipse() function, where the width and + * height of the ellipse are the same. Height and + * width of the ellipse is equal to twice the radius + * of the circle.. By default, the first two + * parameters set the location of the centre of the + * circle, the third sets the radius of the circle. + * @param x x-coordinate of the centre of the circle. + * @param y y-coordinate of the centre of the circle. + * @param r radius of the circle. + * @chainable + */ + circle( + x: number, + y: number, + r: number + ): p5; + /** * Draws a line (a direct path between two points) to * the screen. The version of line() with four @@ -149,7 +172,7 @@ declare module "../../../index" { * the point is determined by the current stroke. * @param x the x-coordinate * @param y the y-coordinate - * @param [z] the z-coordinate (for WEBGL mode) + * @param [z] the z-coordinate (for WebGL mode) * @chainable */ point( @@ -279,9 +302,9 @@ declare module "../../../index" { * @param w width of the rectangle. * @param h height of the rectangle. * @param [detailX] number of segments in the - * x-direction + * x-direction (for WebGL mode) * @param [detailY] number of segments in the - * y-direction + * y-direction (for WebGL mode) * @chainable */ rect( @@ -293,6 +316,44 @@ declare module "../../../index" { detailY?: number ): p5; + /** + * Draws a square to the screen. A square is a + * four-sided shape with every angle at ninety + * degrees, and equal side size. This function is a + * special case of the rect() function, where the + * width and height are the same, and the parameter + * is called "s" for side size. By default, the first + * two parameters set the location of the upper-left + * corner, the third sets the side size of the + * square. The way these parameters are interpreted, + * however, may be changed with the rectMode() + * function. The fourth, fifth, sixth and seventh + * parameters, if specified, determine corner radius + * for the top-left, top-right, lower-right and + * lower-left corners, respectively. An omitted + * corner radius parameter is set to the value of the + * previously specified radius value in the parameter + * list. + * @param x x-coordinate of the square. + * @param y y-coordinate of the square. + * @param s side size of the square. + * @param [tl] optional radius of top-left corner. + * @param [tr] optional radius of top-right corner. + * @param [br] optional radius of bottom-right + * corner. + * @param [bl] optional radius of bottom-left corner. + * @chainable + */ + square( + x: number, + y: number, + s: number, + tl?: number, + tr?: number, + br?: number, + bl?: number + ): p5; + /** * A triangle is a plane created by connecting three * points. The first two arguments specify the first diff --git a/types/p5/src/events/acceleration.d.ts b/types/p5/src/events/acceleration.d.ts index 7c9ea98e2f..1c6f43c7ce 100644 --- a/types/p5/src/events/acceleration.d.ts +++ b/types/p5/src/events/acceleration.d.ts @@ -28,7 +28,8 @@ declare module "../../index" { * The deviceMoved() function is called when the * device is moved by more than the threshold value * along X, Y or Z axis. The default threshold is set - * to 0.5. + * to 0.5. The threshold value can be changed using + * setMoveThreshold(). */ deviceMoved(): void; @@ -48,7 +49,8 @@ declare module "../../index" { * device total acceleration changes of accelerationX * and accelerationY values is more than the * threshold value. The default threshold is set to - * 30. + * 30. The threshold value can be changed using + * setShakeThreshold(). */ deviceShaken(): void; @@ -170,6 +172,13 @@ declare module "../../index" { * rotate direction of the device along the Z-axis. */ pRotationZ: number; + + /** + * When a device is rotated, the axis that triggers + * the deviceTurned() method is stored in the + * turnAxis variable. The turnAxis variable is only + * defined within the scope of deviceTurned(). + */ turnAxis: string; } } diff --git a/types/p5/src/events/keyboard.d.ts b/types/p5/src/events/keyboard.d.ts index 3226d6e741..d7d5fa2d40 100644 --- a/types/p5/src/events/keyboard.d.ts +++ b/types/p5/src/events/keyboard.d.ts @@ -15,12 +15,12 @@ declare module "../../index" { * LEFT_ARROW, RIGHT_ARROW. * * - * For ASCII keys that was pressed is stored in the - * key variable. However, it does not distinguish - * between uppercase and lowercase. For this reason, - * it is recommended to use keyTyped() to read the - * key variable, in which the case of the variable - * will be distinguished. + * For ASCII keys, the key that was pressed is stored + * in the key variable. However, it does not + * distinguish between uppercase and lowercase. For + * this reason, it is recommended to use keyTyped() + * to read the key variable, in which the case of the + * variable will be distinguished. * * * Because of how operating systems handle key diff --git a/types/p5/src/image/p5.Image.d.ts b/types/p5/src/image/p5.Image.d.ts index 08278f9b54..98df046fe0 100644 --- a/types/p5/src/image/p5.Image.d.ts +++ b/types/p5/src/image/p5.Image.d.ts @@ -308,11 +308,11 @@ declare module "../../index" { * second four values (indices 4-7) will contain the * R, G, B, A values of the pixel at (1, 0). More * generally, to set values for a pixel at (x, y): - * var d = pixelDensity(); for (var i = 0; i < d; - * i++) { for (var j = 0; j < d; j++) { // loop over - * idx = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[idx] = r; pixels[idx+1] = g; pixels[idx+2] - * = b; pixels[idx+3] = a; } } + * let d = pixelDensity(); for (let i = 0; i < d; + * i++) { for (let j = 0; j < d; j++) { // loop over + * index = 4 * ((y * d + j) * width * d + (x * d + + * i)); pixels[index] = r; pixels[index+1] = g; + * pixels[index+2] = b; pixels[index+3] = a; } } * * * diff --git a/types/p5/src/image/pixels.d.ts b/types/p5/src/image/pixels.d.ts index 85164e4447..dfdc6b9cfb 100644 --- a/types/p5/src/image/pixels.d.ts +++ b/types/p5/src/image/pixels.d.ts @@ -225,12 +225,16 @@ declare module "../../index" { * is easy, but not as fast as grabbing the data * directly from pixels[]. The equivalent statement * to get(x, y) using pixels[] with pixel density d - * is var x, y, d; // set these to the coordinates - * var off = (y width + x) d * 4; var components = - * [ pixels[off], pixels[off + 1], pixels[off + 2], + * is + * + * let x, y, d; // set these to the coordinates let + * off = (y * width + x) * d * 4; let components = [ + * pixels[off], pixels[off + 1], pixels[off + 2], * pixels[off + 3] ]; print(components); * * + * + * * See the reference for pixels[] for more * information. * @@ -346,11 +350,11 @@ declare module "../../index" { * pixel at (1, 0). More generally, to set values for * a pixel at (x, y): * - * var d = pixelDensity(); for (var i = 0; i < d; - * i++) { for (var j = 0; j < d; j++) { // loop over - * idx = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[idx] = r; pixels[idx+1] = g; pixels[idx+2] - * = b; pixels[idx+3] = a; } } + * let d = pixelDensity(); for (let i = 0; i < d; + * i++) { for (let j = 0; j < d; j++) { // loop over + * index = 4 * ((y * d + j) * width * d + (x * d + + * i)); pixels[index] = r; pixels[index+1] = g; + * pixels[index+2] = b; pixels[index+3] = a; } } * * While the above method is complex, it is flexible * enough to work with any pixelDensity. Note that diff --git a/types/p5/src/io/files.d.ts b/types/p5/src/io/files.d.ts index 75b7eb9a41..5f8c9e059d 100644 --- a/types/p5/src/io/files.d.ts +++ b/types/p5/src/io/files.d.ts @@ -197,6 +197,8 @@ declare module "../../index" { * - tsv - parse the table as tab-separated values * - header - this table has a header (title) row * + * + * * When passing in multiple options, pass them in as * separate parameters, seperated by commas. For * example: @@ -255,6 +257,8 @@ declare module "../../index" { * - tsv - parse the table as tab-separated values * - header - this table has a header (title) row * + * + * * When passing in multiple options, pass them in as * separate parameters, seperated by commas. For * example: @@ -652,22 +656,22 @@ declare module "../../index" { * * * // Saves canvas as an image save('myCanvas.jpg'); - * // Saves pImage as a png image var img = + * // Saves pImage as a png image let img = * createImage(10, 10); save(img, 'my.png'); // Saves - * canvas as an image var cnv = createCanvas(100, + * canvas as an image let cnv = createCanvas(100, * 100); save(cnv, 'myCanvas.jpg'); // Saves - * p5.Renderer object as an image var gb = + * p5.Renderer object as an image let gb = * createGraphics(100, 100); save(gb, - * 'myGraphics.jpg'); var myTable = new p5.Table(); + * 'myGraphics.jpg'); let myTable = new p5.Table(); * // Saves table as html file save(myTable, * 'myTable.html'); // Comma Separated Values * save(myTable, 'myTable.csv'); // Tab Separated - * Values save(myTable, 'myTable.tsv'); var myJSON = + * Values save(myTable, 'myTable.tsv'); let myJSON = * { a: 1, b: true }; // Saves pretty JSON * save(myJSON, 'my.json'); // Optimizes JSON * filesize save(myJSON, 'my.json', true); // Saves * array of strings to a text file with line breaks - * after each item var arrayOfStrings = ['a', 'b']; + * after each item let arrayOfStrings = ['a', 'b']; * save(arrayOfStrings, 'my.txt'); * @param [objectOrFilename] If filename is provided, * will save canvas as an image with either png or diff --git a/types/p5/src/io/p5.XML.d.ts b/types/p5/src/io/p5.XML.d.ts index fe5220e61f..731f63a423 100644 --- a/types/p5/src/io/p5.XML.d.ts +++ b/types/p5/src/io/p5.XML.d.ts @@ -189,5 +189,13 @@ declare module "../../index" { setContent( text: string ): void; + + /** + * Serializes the element into a string. This + * function is useful for preparing the content to be + * sent over a http request or saved to file. + * @return Serialized string of the element + */ + serialize(): string; } } diff --git a/types/p5/src/math/calculation.d.ts b/types/p5/src/math/calculation.d.ts index 82698236c5..cc57b50823 100644 --- a/types/p5/src/math/calculation.d.ts +++ b/types/p5/src/math/calculation.d.ts @@ -101,13 +101,16 @@ declare module "../../index" { * specific increment. The amt parameter is the * amount to interpolate between the two values where * 0.0 equal to the first point, 0.1 is very near the - * first point, 0.5 is half-way in between, etc. The - * lerp function is convenient for creating motion - * along a straight path and for drawing dotted - * lines. + * first point, 0.5 is half-way in between, and 1.0 + * is equal to the second point. If the value of amt + * is more than 1.0 or less than 0.0, the number will + * be calculated accordingly in the ratio of the two + * given numbers. The lerp function is convenient for + * creating motion along a straight path and for + * drawing dotted lines. * @param start first value * @param stop second value - * @param amt number between 0.0 and 1.0 + * @param amt number * @return lerped value */ lerp( diff --git a/types/p5/src/typography/attributes.d.ts b/types/p5/src/typography/attributes.d.ts index 06cb7f9571..cf8a2f651c 100644 --- a/types/p5/src/typography/attributes.d.ts +++ b/types/p5/src/typography/attributes.d.ts @@ -88,12 +88,12 @@ declare module "../../index" { /** * Sets/gets the style of the text for system fonts - * to NORMAL, ITALIC, or BOLD. Note: this may be is - * overridden by CSS styling. For non-system fonts - * (opentype, truetype, etc.) please load styled - * fonts instead. + * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this + * may be is overridden by CSS styling. For + * non-system fonts (opentype, truetype, etc.) please + * load styled fonts instead. * @param theStyle styling for text, either NORMAL, - * ITALIC, or BOLD + * ITALIC, BOLD or BOLDITALIC * @chainable */ textStyle( @@ -102,10 +102,10 @@ declare module "../../index" { /** * Sets/gets the style of the text for system fonts - * to NORMAL, ITALIC, or BOLD. Note: this may be is - * overridden by CSS styling. For non-system fonts - * (opentype, truetype, etc.) please load styled - * fonts instead. + * to NORMAL, ITALIC, BOLD or BOLDITALIC. Note: this + * may be is overridden by CSS styling. For + * non-system fonts (opentype, truetype, etc.) please + * load styled fonts instead. */ textStyle(): string; diff --git a/types/p5/src/typography/loading_displaying.d.ts b/types/p5/src/typography/loading_displaying.d.ts index c02a5d9a4e..35e72263f1 100644 --- a/types/p5/src/typography/loading_displaying.d.ts +++ b/types/p5/src/typography/loading_displaying.d.ts @@ -10,7 +10,7 @@ declare module "../../index" { * method is asynchronous, meaning it may not finish * before the next line in your sketch is executed. * The path to the font should be relative to the - * HTML file that links in your sketch. Loading an + * HTML file that links in your sketch. Loading fonts * from a URL or other remote location may be blocked * due to your browser's built-in security. * @param path name of the file or url to load diff --git a/types/p5/src/typography/p5.Font.d.ts b/types/p5/src/typography/p5.Font.d.ts index 7b6803393e..001540a17a 100644 --- a/types/p5/src/typography/p5.Font.d.ts +++ b/types/p5/src/typography/p5.Font.d.ts @@ -12,7 +12,10 @@ declare module "../../index" { * @param x x-position * @param y y-position * @param [fontSize] font size to use (optional) + * Default is 12. * @param [options] opentype options (optional) + * opentype fonts contains alignment and baseline + * options. Default is 'LEFT' and 'alphabetic' * @return a rectangle object with properties: x, y, * w, h */ diff --git a/types/p5/src/utilities/string_functions.d.ts b/types/p5/src/utilities/string_functions.d.ts index da531a0303..4a46731d7d 100644 --- a/types/p5/src/utilities/string_functions.d.ts +++ b/types/p5/src/utilities/string_functions.d.ts @@ -90,6 +90,14 @@ declare module "../../index" { * formatting floats, and one for formatting ints. * The values for the digits, left, and right * parameters should always be positive integers. + * (NOTE): Be cautious when using left and right + * parameters as it prepends numbers of 0's if the + * parameter if greater than the current length of + * the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param num the Number to format * @param [left] number of digits to the left of the * decimal point @@ -115,6 +123,14 @@ declare module "../../index" { * formatting floats, and one for formatting ints. * The values for the digits, left, and right * parameters should always be positive integers. + * (NOTE): Be cautious when using left and right + * parameters as it prepends numbers of 0's if the + * parameter if greater than the current length of + * the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param nums the Numbers to format * @param [left] number of digits to the left of the * decimal point @@ -216,12 +232,27 @@ declare module "../../index" { /** * Utility function for formatting numbers into - * strings. Similar to nf() but puts a " " (space) in - * front of positive numbers and a "-" in front of - * negative numbers. There are two versions: one for - * formatting floats, and one for formatting ints. - * The values for the digits, left, and right - * parameters should always be positive integers. + * strings. Similar to nf() but puts an additional + * "_" (space) in front of positive numbers just in + * case to align it with negative numbers which + * includes "-" (minus) sign. The main usecase of + * nfs() can be seen when one wants to align the + * digits (place values) of a positive number with + * some negative number (See the example to get a + * clear picture). There are two versions: one for + * formatting float, and one for formatting int. The + * values for the digits, left, and right parameters + * should always be positive integers. (IMP): The + * result on the canvas basically the expected + * alignment can vary based on the typeface you are + * using. (NOTE): Be cautious when using left and + * right parameters as it prepends numbers of 0's if + * the parameter if greater than the current length + * of the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param num the Number to format * @param [left] number of digits to the left of the * decimal point @@ -237,12 +268,27 @@ declare module "../../index" { /** * Utility function for formatting numbers into - * strings. Similar to nf() but puts a " " (space) in - * front of positive numbers and a "-" in front of - * negative numbers. There are two versions: one for - * formatting floats, and one for formatting ints. - * The values for the digits, left, and right - * parameters should always be positive integers. + * strings. Similar to nf() but puts an additional + * "_" (space) in front of positive numbers just in + * case to align it with negative numbers which + * includes "-" (minus) sign. The main usecase of + * nfs() can be seen when one wants to align the + * digits (place values) of a positive number with + * some negative number (See the example to get a + * clear picture). There are two versions: one for + * formatting float, and one for formatting int. The + * values for the digits, left, and right parameters + * should always be positive integers. (IMP): The + * result on the canvas basically the expected + * alignment can vary based on the typeface you are + * using. (NOTE): Be cautious when using left and + * right parameters as it prepends numbers of 0's if + * the parameter if greater than the current length + * of the number. For example if number is 123.2 and + * left parameter passed is 4 which is greater than + * length of 123 (integer part) i.e 3 than result + * will be 0123.2. Same case for right parameter i.e. + * if right is 3 than the result will be 123.200. * @param nums the Numbers to format * @param [left] number of digits to the left of the * decimal point diff --git a/types/p5/src/webgl/material.d.ts b/types/p5/src/webgl/material.d.ts index 09f392d7e8..ecdf389ee7 100644 --- a/types/p5/src/webgl/material.d.ts +++ b/types/p5/src/webgl/material.d.ts @@ -63,6 +63,23 @@ declare module "../../index" { | Graphics ): p5; + /** + * Sets the coordinate space for texture mapping. The + * default mode is IMAGE which refers to the actual + * coordinates of the image. NORMAL refers to a + * normalized space of values ranging from 0 to 1. + * This function only works in WEBGL mode. With + * IMAGE, if an image is 100 x 200 pixels, mapping + * the image onto the entire size of a quad would + * require the points (0,0) (100, 0) (100,200) + * (0,200). The same mapping in NORMAL is (0,0) (1,0) + * (1,1) (0,1). + * @param mode either IMAGE or NORMAL + */ + textureMode( + mode: TEXTURE_MODE + ): void; + /** * Ambient material for geometry with a given color. * You can view all possible materials in this From 3b1eee6c0c06c7b79856d1522d175b892cc34a26 Mon Sep 17 00:00:00 2001 From: Sergey Shandar Date: Thu, 24 Jan 2019 10:52:34 -0800 Subject: [PATCH 065/312] NodeType type --- types/commonmark/index.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index 96bb2774c5..9af9f0e23b 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -4,15 +4,18 @@ // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export type NodeType = + 'text' |'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | + 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block' + export class Node { - constructor(nodeType: string, sourcepos?: Position); + constructor(nodeType: NodeType, sourcepos?: Position); /** * (read-only): a String, one of text, softbreak, linebreak, emph, strong, html_inline, link, image, code, document, paragraph, * block_quote, item, list, heading, code_block, html_block, thematic_break. */ - readonly type: 'text' | 'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | - 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + readonly type: NodeType; /** * (read-only): a Node or null. */ From a625d316c5433fd14ca6cef925b75cf942b7293b Mon Sep 17 00:00:00 2001 From: Sergey Shandar Date: Thu, 24 Jan 2019 16:50:17 -0800 Subject: [PATCH 066/312] Update index.d.ts --- types/commonmark/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index 9af9f0e23b..2f2899b44a 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -4,9 +4,9 @@ // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type NodeType = +export type NodeType = 'text' |'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | - 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block' + 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; export class Node { constructor(nodeType: NodeType, sourcepos?: Position); From e92ff96b548a1056de14b2a1f1f905f9826abbc9 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Fri, 25 Jan 2019 10:18:29 +0100 Subject: [PATCH 067/312] Add tests --- types/enzyme/enzyme-tests.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 0711243d0c..879f06dc3c 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -35,6 +35,10 @@ interface MyComponentState { stateProperty: string; } +function toComponentType(Component: ComponentClass | StatelessComponent): ComponentClass | StatelessComponent { + return Component; +} + class MyComponent extends Component { handleEcho(value: string) { return value; @@ -59,6 +63,8 @@ const MyStatelessComponent = (props: StatelessProps) => ; const AnotherStatelessComponent = (props: AnotherStatelessProps) => ; +const ComponentType = toComponentType(MyComponent); + // Enzyme.configure function configureTest() { const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; @@ -859,6 +865,14 @@ function ReactWrapperTest() { reactWrapper = new ReactWrapper(, undefined, { attachTo: document.createElement('div') }); reactWrapper = new ReactWrapper(, reactWrapper, { attachTo: document.createElement('div') }); } + + function test_component_type() { + const wrapper1 = shallow(
    ); + wrapper1.find(ComponentType); + + const wrapper2 = mount(
    ); + wrapper2.find(ComponentType); + } } // CheerioWrapper From ac3723c88c23ff542e76539faa014f4cfce59176 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 24 Jan 2019 19:31:17 +0100 Subject: [PATCH 068/312] [README] improve FAQ section on module interop schemes --- README.md | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4343577bd0..97dead214e 100644 --- a/README.md +++ b/README.md @@ -255,12 +255,30 @@ Here are the [currently requested definitions](https://github.com/DefinitelyType If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`. +#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? + +Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. + +Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: + +> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct + +This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. +This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. + +It is more appropriate to import the module using the `import foo = require("foo");` syntax. +Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options: +- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm). +- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7). + #### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`? -If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project. -Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option. +Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) +or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) +compiler options. + Do not change the type definition if it is accurate. -For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export. +For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module. #### I want to use features from TypeScript 2.1 or above. @@ -368,19 +386,6 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead. -#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? - -Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. - -Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: - -> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct - -This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. -This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. - -It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such. - ## License This project is licensed under the MIT license. From f2d7483269a697f3de8dd5b07e50d7aa4c1cfa0e Mon Sep 17 00:00:00 2001 From: Lee Henson Date: Fri, 25 Jan 2019 11:48:10 +0000 Subject: [PATCH 069/312] [http-aws-es] update ConfigOptions to support awsConfig key --- types/http-aws-es/http-aws-es-tests.ts | 8 ++++---- types/http-aws-es/index.d.ts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/http-aws-es/http-aws-es-tests.ts b/types/http-aws-es/http-aws-es-tests.ts index df432dbab4..acd5248817 100644 --- a/types/http-aws-es/http-aws-es-tests.ts +++ b/types/http-aws-es/http-aws-es-tests.ts @@ -3,7 +3,7 @@ import { Client } from "elasticsearch"; import HttpAmazonESConnector = require("http-aws-es"); new Client({ - amazonES: { + awsConfig: { accessKey: "AKID", region: "us-east-1", secretKey: "secret", @@ -13,7 +13,7 @@ new Client({ }); new Client({ - amazonES: { + awsConfig: { accessKey: "AKID", region: "us-east-1", secretKey: "secret", @@ -24,7 +24,7 @@ new Client({ const myCredentials = new EnvironmentCredentials("AWS"); new Client({ - amazonES: { + awsConfig: { credentials: myCredentials, region: "us-east-1", }, @@ -33,7 +33,7 @@ new Client({ }); new Client({ - amazonES: { + awsConfig: { credentials: myCredentials, region: "us-east-1", }, diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index 91e12604f8..15a803076f 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-aws-es 1.1 +// Type definitions for http-aws-es 6.0 // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,7 +18,7 @@ declare module "elasticsearch" { } interface ConfigOptions { - amazonES?: AmazonESOptions; + awsConfig?: AmazonESOptions; } } From f015edd8d668da41a5131b4b4d3296861d288f2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danilo=20B=C3=BCrger?= Date: Fri, 25 Jan 2019 11:19:05 +0100 Subject: [PATCH 070/312] [react-native-fbsdk] Added AppEventsLogger.setUserID --- types/react-native-fbsdk/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts index eacc05209e..5049669e35 100644 --- a/types/react-native-fbsdk/index.d.ts +++ b/types/react-native-fbsdk/index.d.ts @@ -639,6 +639,12 @@ export namespace AppEventsLogger { */ function flush(): void; + /** + * Sets a custom user ID to associate with all app events. + * The userID is persisted until it is cleared by passing nil. + */ + function setUserID(userID: string | null): void; + /** * For iOS only, sets and sends device token to register the current application for push notifications. * @platform ios From 2c41a9f8f259e1cb6c7a3509c7531da311f7351b Mon Sep 17 00:00:00 2001 From: "s.maliauka" Date: Fri, 25 Jan 2019 18:21:11 +0300 Subject: [PATCH 071/312] lory.js: update to match lory.js 2.5.3 API --- types/lory.js/index.d.ts | 7 ++++++- types/lory.js/lory.js-tests.ts | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/types/lory.js/index.d.ts b/types/lory.js/index.d.ts index dd37fb8efa..82c1f6fbc6 100644 --- a/types/lory.js/index.d.ts +++ b/types/lory.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lory 2.2.1 +// Type definitions for lory 2.5.3 // Project: https://github.com/meandmax/lory/ // Definitions by: kubosho // philip bulley @@ -80,6 +80,11 @@ interface LoryOptions { * cubic bezier easing functions: http://easings.net/de (default: 'cubic-bezier(0.455, 0.03, 0.515, 0.955)'). */ ease?: string; + + /** + * the slide index to show when the slider is initialized ( default: 0 ) + */ + initialIndex?: number; /** * if slider reached the last slide, with next click the slider goes back to the startindex (default: false). diff --git a/types/lory.js/lory.js-tests.ts b/types/lory.js/lory.js-tests.ts index 616073f180..f3ca0464c2 100644 --- a/types/lory.js/lory.js-tests.ts +++ b/types/lory.js/lory.js-tests.ts @@ -19,6 +19,7 @@ import { lory } from 'lory.js'; rewindSpeed: 600, snapBackSpeed: 200, ease: 'ease', + initialIndex: 0, rewind: true, infinite: false, classNameFrame: 'js_frame', From 1c8707a34aff01b2d69b35a389549f082d0f0467 Mon Sep 17 00:00:00 2001 From: Brian Schiller Date: Fri, 25 Jan 2019 11:03:55 -0700 Subject: [PATCH 072/312] puppeteer: safer args for page.eval and friends page.evaluate and similar functions are currently typed as if they accept 'any' args, but they will throw exceptions unless the args are either Serializable (with JSON.stringify) or JSHandles. In GoogleChrome/puppeteer#3591, @SimonSchick recommended that tighter type definitions was a preferable way to address this rather than runtime error checking. I've been using these updated types in my project for the last couple of months without problem. I suspect that some of the X1, X2 type parameters should also be changed to reflect that they can only be SerializableOrJSHandle, but I wasn't sure how to change the existing UnwrapElementHandle types. --- types/puppeteer/index.d.ts | 41 +++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index bd65a70455..66c73e1f96 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -18,6 +18,19 @@ export type WrapElementHandle = X extends Element ? ElementHandle : X; /** Unwraps a DOM element out of an ElementHandle instance */ export type UnwrapElementHandle = X extends ElementHandle ? E : X; +export type Serializable = + | number + | string + | boolean + | null + | JSONArray + | JSONObject; +export interface JSONArray extends Array { } +export interface JSONObject { + [key: string]: Serializable; +} +export type SerializableOrJSHandle = Serializable | JSHandle; + /** Defines `$eval` and `$$eval` for Page, Frame and ElementHandle. */ export interface Evalable { /** @@ -106,7 +119,7 @@ export interface Evalable { $eval( selector: string, pageFunction: (element: Element, ...args: any[]) => R | Promise, - ...args: any[], + ...args: SerializableOrJSHandle[], ): Promise>; /** @@ -195,7 +208,7 @@ export interface Evalable { $$eval( selector: string, pageFunction: (elements: Element[], ...args: any[]) => R | Promise, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise>; } @@ -718,7 +731,7 @@ export interface Worker { */ evaluate( pageFunction: (...args: any[]) => T | Promise, - ...args: any[], + ...args: SerializableOrJSHandle[], ): Promise; /** @@ -727,7 +740,7 @@ export interface Worker { */ evaluateHandle( pageFunction: (...args: any[]) => T | Promise, - ...args: any[], + ...args: SerializableOrJSHandle[], ): Promise; executionContext(): Promise; @@ -830,11 +843,11 @@ export interface ElementHandle extends JSHandle, Ev export interface ExecutionContext { evaluate( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; evaluateHandle( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; queryObjects(prototypeHandle: JSHandle): JSHandle; } @@ -1141,7 +1154,7 @@ export interface FrameBase extends Evalable { */ evaluate( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; /** @@ -1154,7 +1167,7 @@ export interface FrameBase extends Evalable { */ evaluateHandle( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; /** This method fetches an element with selector and focuses it. */ @@ -1219,7 +1232,11 @@ export interface FrameBase extends Evalable { /** * Shortcut for waitForFunction. */ - waitFor(selector: ((...args: any[]) => any) | string, options?: WaitForSelectorOptions, ...args: any[]): Promise; + waitFor( + selector: ((...args: any[]) => any) | string, + options?: WaitForSelectorOptions, + ...args: SerializableOrJSHandle[] + ): Promise; /** * Allows waiting for various conditions. @@ -1227,7 +1244,7 @@ export interface FrameBase extends Evalable { waitForFunction( fn: string | ((...args: any[]) => any), options?: PageFnOptions, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; /** @@ -1539,7 +1556,7 @@ export interface Page extends EventEmitter, FrameBase { */ evaluateHandle( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; /** @@ -1550,7 +1567,7 @@ export interface Page extends EventEmitter, FrameBase { */ evaluateOnNewDocument( fn: EvaluateFn, - ...args: any[] + ...args: SerializableOrJSHandle[] ): Promise; /** From 9da592449acf59398b35af0d2e6c7f9dc13eddf0 Mon Sep 17 00:00:00 2001 From: ppenelon Date: Fri, 25 Jan 2019 20:30:38 +0000 Subject: [PATCH 073/312] Update getDecoratedValue method type Avoid Typescript compilation to let DecoratedPolicyOptions be extends as PolicyOptions because the getDecoratedValue property was optionnal. --- types/catbox/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 32fbdf6f3f..bd41889e07 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -231,7 +231,7 @@ export interface DecoratedPolicyOptions extends PolicyOptions { /** * @default false */ - getDecoratedValue?: boolean; + getDecoratedValue: boolean | undefined; } export interface GenerateFuncFlags { From 0b1cc5b5162a246a70fce0dd3d0f6b457afaf89f Mon Sep 17 00:00:00 2001 From: Dave Cardwell Date: Fri, 25 Jan 2019 20:38:27 -0500 Subject: [PATCH 074/312] [qs-middleware] Add initial types --- types/qs-middleware/index.d.ts | 14 +++++++++++++ types/qs-middleware/qs-middleware-tests.ts | 23 ++++++++++++++++++++++ types/qs-middleware/tsconfig.json | 16 +++++++++++++++ types/qs-middleware/tslint.json | 1 + 4 files changed, 54 insertions(+) create mode 100644 types/qs-middleware/index.d.ts create mode 100644 types/qs-middleware/qs-middleware-tests.ts create mode 100644 types/qs-middleware/tsconfig.json create mode 100644 types/qs-middleware/tslint.json diff --git a/types/qs-middleware/index.d.ts b/types/qs-middleware/index.d.ts new file mode 100644 index 0000000000..9817c7bd79 --- /dev/null +++ b/types/qs-middleware/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for qs-middleware 1.0 +// Project: https://github.com/springernature/qs-middleware +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require("express"); +import qs = require("qs"); + +declare function qsMiddleware( + options?: qs.IParseOptions +): express.RequestHandler; + +export = qsMiddleware; diff --git a/types/qs-middleware/qs-middleware-tests.ts b/types/qs-middleware/qs-middleware-tests.ts new file mode 100644 index 0000000000..b77d265756 --- /dev/null +++ b/types/qs-middleware/qs-middleware-tests.ts @@ -0,0 +1,23 @@ +import express = require("express"); +import query = require("qs-middleware"); + +const app = express(); + +app.use(query()); +app.use(query({})); +app.use( + query({ + delimiter: "string", + depth: 123, + decoder: str => str.toLowerCase(), + arrayLimit: 123, + parseArrays: true, + allowDots: true, + plainObjects: true, + allowPrototypes: true, + parameterLimit: 123, + strictNullHandling: true, + ignoreQueryPrefix: true + }) +); +app.use(query({ delimiter: /regexp/ })); diff --git a/types/qs-middleware/tsconfig.json b/types/qs-middleware/tsconfig.json new file mode 100644 index 0000000000..b984b327ed --- /dev/null +++ b/types/qs-middleware/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", "qs-middleware-tests.ts"] +} diff --git a/types/qs-middleware/tslint.json b/types/qs-middleware/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/qs-middleware/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9699c212d2b4e86481a247eaa6de81cbe58c3713 Mon Sep 17 00:00:00 2001 From: Hiroshi Ioka Date: Wed, 23 Jan 2019 08:02:50 +0900 Subject: [PATCH 075/312] @types/koa-session: support missing options --- types/koa-session/index.d.ts | 25 +++++++------------------ types/koa-session/koa-session-tests.ts | 1 + types/koa2-session-redis/index.d.ts | 2 +- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/types/koa-session/index.d.ts b/types/koa-session/index.d.ts index 08e6e66f70..512b888e1c 100644 --- a/types/koa-session/index.d.ts +++ b/types/koa-session/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for koa-session 5.7 +// Type definitions for koa-session 5.10 // Project: https://github.com/koajs/session // Definitions by: Yu Hsin Lu // Tomek Łaziuk +// Hiroshi Ioka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /* =================== USAGE =================== @@ -16,6 +17,9 @@ =============================================== */ import Koa = require("koa"); +import Cookies = require("cookies"); + +type Omit = Pick>; declare namespace session { /** @@ -108,7 +112,7 @@ declare namespace session { hash(sess: any): string; } - interface opts { + interface opts extends Omit { /** * cookie key (default is koa:sess) */ @@ -121,21 +125,6 @@ declare namespace session { */ maxAge?: number | "session"; - /** - * can overwrite or not (default true) - */ - overwrite: boolean; - - /** - * httpOnly or not (default true) - */ - httpOnly: boolean; - - /** - * signed or not (default true) - */ - signed: boolean; - /** * custom encode method */ diff --git a/types/koa-session/koa-session-tests.ts b/types/koa-session/koa-session-tests.ts index a647b43e42..4930a6f1c2 100644 --- a/types/koa-session/koa-session-tests.ts +++ b/types/koa-session/koa-session-tests.ts @@ -37,6 +37,7 @@ app.use(session({ console.log(key); }, }, + path: "/", }, app)); app.use((ctx, next) => { diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts index 24e85e1674..049c655f5f 100644 --- a/types/koa2-session-redis/index.d.ts +++ b/types/koa2-session-redis/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/lonord/koa2-session-redis // Definitions by: Dima Mukhin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as Redis from 'redis'; import * as session from 'koa-session'; From 0b537cf0862e31ce5ee6970ea6cc59d3e20cb1e5 Mon Sep 17 00:00:00 2001 From: Nick Zahn Date: Sat, 26 Jan 2019 09:37:55 +0000 Subject: [PATCH 076/312] [xxhashjs] Upgrade to 0.2, fix return type --- types/xxhashjs/index.d.ts | 22 +++++++++++++----- types/xxhashjs/xxhashjs-tests.ts | 38 ++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/types/xxhashjs/index.d.ts b/types/xxhashjs/index.d.ts index 40c45cf3ab..9c9d7e4318 100644 --- a/types/xxhashjs/index.d.ts +++ b/types/xxhashjs/index.d.ts @@ -1,19 +1,29 @@ -// Type definitions for xxhashjs 0.1 +// Type definitions for xxhashjs 0.2 // Project: https://github.com/pierrec/js-xxhash // Definitions by: Dibyo Majumdar +// Nick Zahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + export as namespace XXH; +// Ideally we would have a type definition for the "cuint" package. +// The following interface `UINT` is to resolve the bare minimum. +interface UINT { + toNumber(): number; + toString(radix?: number): string; +} + export interface HashObject { - init(seed: number): this; - update(data: string | ArrayBuffer): this; - digest(): number; + init(seed: number): this; + update(data: string | ArrayBuffer | Buffer): this; + digest(): UINT; } export interface HashInterface { - (seed?: number): HashObject; - (data: string | ArrayBuffer, seed: number): number; + (seed?: number): HashObject; + (data: string | ArrayBuffer | Buffer, seed: number): UINT; } export const h32: HashInterface; diff --git a/types/xxhashjs/xxhashjs-tests.ts b/types/xxhashjs/xxhashjs-tests.ts index ee2d7ef8f3..889bf9bb40 100644 --- a/types/xxhashjs/xxhashjs-tests.ts +++ b/types/xxhashjs/xxhashjs-tests.ts @@ -1,7 +1,37 @@ import XXH from 'xxhashjs'; -// examples adapted from https://github.com/pierrec/js-xxhash -const h1 = XXH.h32('abcd', 0xABCD).toString(16); +// Test data +const seed = 0xABCD; +const stringData = 'abcd'; +const arrayBufferData = new ArrayBuffer(4); +const bufferData = Buffer.from([1, 2, 3, 4]); -const H = XXH.h32(0xABCD); -const h2 = H.update('abcd').digest().toString(16); +// Test XXH.h32 methods, initialising with string data +const value32_1 = XXH.h32(stringData, seed); +value32_1.toString(); +value32_1.toString(16); +value32_1.toNumber(); + +const value32_2 = XXH.h32(seed).update(stringData).digest(); +value32_2.toString(); +value32_2.toString(16); +value32_2.toNumber(); + +// Test XXH.h64 methods, initialising with string data +const value64_1 = XXH.h64(stringData, seed); +value64_1.toString(); +value64_1.toString(16); +value64_1.toNumber(); + +const value64_2 = XXH.h64(seed).update(stringData).digest(); +value64_2.toString(); +value64_2.toString(16); +value64_2.toNumber(); + +// Initialise with ArrayBuffer +XXH.h32(arrayBufferData, seed); +XXH.h64(arrayBufferData, seed); + +// Initialise with Buffer +XXH.h32(bufferData, seed); +XXH.h64(bufferData, seed); From 808caa887efbf8445fad4fd8058c100e276ba88d Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Sat, 26 Jan 2019 19:42:06 +0800 Subject: [PATCH 077/312] add dom to compilerOptions --- types/redux-state-sync/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/redux-state-sync/tsconfig.json b/types/redux-state-sync/tsconfig.json index e2c1dcbede..dd15d9a067 100644 --- a/types/redux-state-sync/tsconfig.json +++ b/types/redux-state-sync/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, From daac60683d589dc6dd84ad6c61f9c0a9bd4a7b3d Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Sat, 26 Jan 2019 13:08:10 +0100 Subject: [PATCH 078/312] Update enzyme-tests.tsx --- types/enzyme/enzyme-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 879f06dc3c..b92f553584 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -868,10 +868,10 @@ function ReactWrapperTest() { function test_component_type() { const wrapper1 = shallow(
    ); - wrapper1.find(ComponentType); + wrapper1.find(ComponentType).props().stringProp; // $ExpectType string const wrapper2 = mount(
    ); - wrapper2.find(ComponentType); + wrapper2.find(ComponentType).props().stringProp; // $ExpectType string } } From fba358da45c6dda900a64c299bb08055de535e65 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Sat, 26 Jan 2019 13:27:05 +0100 Subject: [PATCH 079/312] Update enzyme-tests.tsx --- types/enzyme/enzyme-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index b92f553584..0c7e2c2e90 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -868,10 +868,10 @@ function ReactWrapperTest() { function test_component_type() { const wrapper1 = shallow(
    ); - wrapper1.find(ComponentType).props().stringProp; // $ExpectType string + wrapper1.find(ComponentType).props().stringProp; // $ExpectType string const wrapper2 = mount(
    ); - wrapper2.find(ComponentType).props().stringProp; // $ExpectType string + wrapper2.find(ComponentType).props().stringProp; // $ExpectType string } } From 77bdd906d210fae0519283cc14d83749c8ed486c Mon Sep 17 00:00:00 2001 From: tell-y Date: Sun, 27 Jan 2019 00:29:03 +0900 Subject: [PATCH 080/312] add rx and ry props to Svg.Rect --- types/expo/index.d.ts | 2 ++ types/expo/v24/index.d.ts | 2 ++ types/expo/v25/index.d.ts | 2 ++ types/expo/v26/index.d.ts | 2 ++ types/expo/v27/index.d.ts | 2 ++ types/expo/v30/index.d.ts | 2 ++ 6 files changed, 12 insertions(+) diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 1b24c3151c..c206bc12ff 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -2451,6 +2451,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v24/index.d.ts b/types/expo/v24/index.d.ts index 35d1e9be92..7c515a0268 100644 --- a/types/expo/v24/index.d.ts +++ b/types/expo/v24/index.d.ts @@ -1949,6 +1949,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v25/index.d.ts b/types/expo/v25/index.d.ts index 766c055911..9e2da6c790 100644 --- a/types/expo/v25/index.d.ts +++ b/types/expo/v25/index.d.ts @@ -1978,6 +1978,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 9804579e66..e8386db63c 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -2006,6 +2006,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v27/index.d.ts b/types/expo/v27/index.d.ts index a80fb657ee..179315ba69 100644 --- a/types/expo/v27/index.d.ts +++ b/types/expo/v27/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v30/index.d.ts b/types/expo/v30/index.d.ts index d5891bad2d..8a77777c49 100644 --- a/types/expo/v30/index.d.ts +++ b/types/expo/v30/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { From db4a0483d5ea2bfd56d320e36930a98338049d05 Mon Sep 17 00:00:00 2001 From: Ben Date: Sat, 26 Jan 2019 14:45:28 -0500 Subject: [PATCH 081/312] add types for react-ultimate-pagination --- types/react-ultimate-pagination/index.d.ts | 121 ++++++++++++++++++ .../react-ultimate-pagination-tests.tsx | 53 ++++++++ types/react-ultimate-pagination/tsconfig.json | 23 ++++ types/react-ultimate-pagination/tslint.json | 1 + 4 files changed, 198 insertions(+) create mode 100644 types/react-ultimate-pagination/index.d.ts create mode 100644 types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx create mode 100644 types/react-ultimate-pagination/tsconfig.json create mode 100644 types/react-ultimate-pagination/tslint.json diff --git a/types/react-ultimate-pagination/index.d.ts b/types/react-ultimate-pagination/index.d.ts new file mode 100644 index 0000000000..8e2c917d75 --- /dev/null +++ b/types/react-ultimate-pagination/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for react-ultimate-pagination 1.2 +// Project: https://github.com/ultimate-pagination/react-ultimate-pagination +// Definitions by: Ben Lorantfy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +import * as React from "react"; + +export interface PaginationComponentProps { + /** + * Number of pages that user should navigate to when item is activated (for items with type `PAGE` it also can be used as a label in UI) + */ + value: number; + + /** + * Show if `currentPage` if the same as `value` of an item (can be used to highlight a current page or disable first, previous, next or last page links when user is already on first/last page) + */ + isActive: boolean; + + /** + * Show if button should be disabled + */ + isDisabled: boolean; + + /** + * Should be called when user interacted with a component and the current page should be changed to the page represented by item (no arguments should be used, can be used for all item types) + */ + onClick: () => void; +} + +export interface ItemTypeToComponent { + /** + * A link to a page + */ + PAGE: React.ComponentType, + + /** + * An item that represents groups of pages that currently are not visible in paginator (can be used to navigate to the page in the group that is the nearest to the current page) + */ + ELLIPSIS: React.ComponentType, + + /** + * A link to the first page + */ + FIRST_PAGE_LINK: React.ComponentType, + + /** + * A link to the previous page + */ + PREVIOUS_PAGE_LINK: React.ComponentType, + + /** + * A link to the next page + */ + NEXT_PAGE_LINK: React.ComponentType, + + /** + * A link to the last page + */ + LAST_PAGE_LINK: React.ComponentType, +} + +export interface CreateUltimatePaginationOptions { + /** + * An object that is used as a map from the item type to the React.js component that will be used to render this item + */ + itemTypeToComponent: ItemTypeToComponent; + + /** + * A React.js component that will be used as a wrapper for pagination items + */ + WrapperComponent: string|React.ComponentType; +} + +export interface UltimatePaginationProps { + /** + * Current page number + */ + currentPage: number; + + /** + * Total number of pages + */ + totalPages: number; + + /** + * Number of always visible pages at the beginning and end + */ + boundaryPagesRange?: number; + + /** + * Number of always visible pages before and after the current one + */ + siblingPagesRange?: number; + + /** + * Boolean flag to hide ellipsis + */ + hideEllipsis?: boolean; + + /** + * Boolean flag to hide previous and next page links + */ + hidePreviousAndNextPageLinks?: boolean; + + /** + * Boolean flag to hide first and last page links + */ + hideFirstAndLastPageLinks?: boolean; + + /** + * Callback that will be called with new page when it should be changed by user interaction + */ + onChange?: (newPage: number) => void; + + /** + * Boolean flag to disable all buttons in pagination + */ + disabled?: boolean; +} + +export function createUltimatePagination(options: CreateUltimatePaginationOptions): React.ComponentType; diff --git a/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx new file mode 100644 index 0000000000..8116f5e42b --- /dev/null +++ b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx @@ -0,0 +1,53 @@ +import * as React from "react"; +import { + PaginationComponentProps, + createUltimatePagination, + ItemTypeToComponent +} from "react-ultimate-pagination"; + +function Page(props: PaginationComponentProps) { + return ( + + ); +} + +function Ellipsis(props: PaginationComponentProps) { + return ; +} + +function FirstPageLink(props: PaginationComponentProps) { + return ; +} + +function PreviousPageLink(props: PaginationComponentProps) { + return ; +} + +function NextPageLink(props: PaginationComponentProps) { + return ; +} + +function LastPageLink(props: PaginationComponentProps) { + return ; +} + +function Wrapper(props: { children: React.ReactChildren }) { + return
    {props.children}
    ; +} + +const itemTypeToComponent: ItemTypeToComponent = { + PAGE: Page, + ELLIPSIS: Ellipsis, + FIRST_PAGE_LINK: FirstPageLink, + PREVIOUS_PAGE_LINK: PreviousPageLink, + NEXT_PAGE_LINK: NextPageLink, + LAST_PAGE_LINK: LastPageLink +}; + +const UltimatePagination = createUltimatePagination({ itemTypeToComponent, WrapperComponent: Wrapper }); // $ExpectType React.ComponentType + +; diff --git a/types/react-ultimate-pagination/tsconfig.json b/types/react-ultimate-pagination/tsconfig.json new file mode 100644 index 0000000000..b16cb5d3d0 --- /dev/null +++ b/types/react-ultimate-pagination/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-ultimate-pagination-tests.tsx" + ] +} diff --git a/types/react-ultimate-pagination/tslint.json b/types/react-ultimate-pagination/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-ultimate-pagination/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2b104c6fe8d6822d5adbf1bcdfc49e0e0e7421a6 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 26 Jan 2019 21:05:33 +0100 Subject: [PATCH 082/312] improve(buble): prefer use "SourceMap" type from official package, instead of manually defining it --- types/buble/index.d.ts | 8 ++++---- types/buble/package.json | 6 ++++++ 2 files changed, 10 insertions(+), 4 deletions(-) create mode 100644 types/buble/package.json diff --git a/types/buble/index.d.ts b/types/buble/index.d.ts index c222d08e87..af2a7e26ee 100644 --- a/types/buble/index.d.ts +++ b/types/buble/index.d.ts @@ -2,6 +2,9 @@ // Project: https://github.com/Rich-Harris/buble#README // Definitions by: Kocal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { SourceMap } from "magic-string"; export interface TransformOptions { // source: https://github.com/Rich-Harris/buble/blob/master/src/support.js @@ -56,10 +59,7 @@ export interface TransformOptions { export interface TransformOutput { code: string; - map: { - toString(): string; - toUrl(): string; - }; + map: SourceMap; } export function transform(content: string, options?: TransformOptions): TransformOutput; diff --git a/types/buble/package.json b/types/buble/package.json new file mode 100644 index 0000000000..d2f8119c0a --- /dev/null +++ b/types/buble/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "magic-string": "^0.25.0" + } +} From 09e60dac8834e571d58f90bc5832c909dd356a3b Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 26 Jan 2019 21:20:18 +0100 Subject: [PATCH 083/312] fix(buble): "toUrl()" is a method, not a property --- types/buble/buble-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/buble/buble-tests.ts b/types/buble/buble-tests.ts index e786ee6854..cebb373415 100644 --- a/types/buble/buble-tests.ts +++ b/types/buble/buble-tests.ts @@ -8,7 +8,7 @@ const input = 'const answer = () => 42;'; console.log(output.code); console.log(output.map.toString()); - console.log(output.map.toUrl); + console.log(output.map.toUrl()); })(); // Transform for Chrome & Firefox From 18de647d22cf0c498173e5b650883659653e3622 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 26 Jan 2019 21:31:52 +0100 Subject: [PATCH 084/312] chore: setup type --- types/rollup-plugin-node-builtins/index.d.ts | 5 ++++ .../rollup-plugin-node-builtins-tests.ts | 0 .../rollup-plugin-node-builtins/tsconfig.json | 23 +++++++++++++++++++ types/rollup-plugin-node-builtins/tslint.json | 1 + 4 files changed, 29 insertions(+) create mode 100644 types/rollup-plugin-node-builtins/index.d.ts create mode 100644 types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts create mode 100644 types/rollup-plugin-node-builtins/tsconfig.json create mode 100644 types/rollup-plugin-node-builtins/tslint.json diff --git a/types/rollup-plugin-node-builtins/index.d.ts b/types/rollup-plugin-node-builtins/index.d.ts new file mode 100644 index 0000000000..70f8b3c873 --- /dev/null +++ b/types/rollup-plugin-node-builtins/index.d.ts @@ -0,0 +1,5 @@ +// Type definitions for rollup-plugin-node-builtins 2.1 +// Project: https://github.com/calvinmetcalf/rollup-plugin-node-builtins#readme +// Definitions by: Kocal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + diff --git a/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts b/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/rollup-plugin-node-builtins/tsconfig.json b/types/rollup-plugin-node-builtins/tsconfig.json new file mode 100644 index 0000000000..c0a6e1e787 --- /dev/null +++ b/types/rollup-plugin-node-builtins/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", + "rollup-plugin-node-builtins-tests.ts" + ] +} diff --git a/types/rollup-plugin-node-builtins/tslint.json b/types/rollup-plugin-node-builtins/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-node-builtins/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6d9de2a5d985e2dd8c7fa94505ab3ee7875e1f51 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 21:40:46 +0100 Subject: [PATCH 085/312] Add info about native balance --- types/coinbase/index.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 6057f58142..6731ff3a79 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -536,6 +536,21 @@ export class Account implements Resource { */ balance: MoneyHash; + /** + * Allow deposits + */ + allow_deposits: boolean; + + /** + * Allow withdrawls + */ + allow_withdrawals: boolean; + + /** + * Account worth in native balance. + */ + native_balance: MoneyHash; + /** * Promote an account as primary account. * Scope: wallet:accounts:update From 4962cb4cfdda1122a9efcda11f1ad87927f38561 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 21:44:46 +0100 Subject: [PATCH 086/312] v2.0.8 --- types/coinbase/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 6731ff3a79..1ef91bbcbb 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for coinbase 2.0 +// Type definitions for coinbase 2.0.8 // Project: https://github.com/coinbase/coinbase-node // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 7e7b62dfcc7f8a19a7c610f85b3e25ba46ccf5f9 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 21:51:10 +0100 Subject: [PATCH 087/312] Update index.d.ts --- types/coinbase/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 1ef91bbcbb..6731ff3a79 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for coinbase 2.0.8 +// Type definitions for coinbase 2.0 // Project: https://github.com/coinbase/coinbase-node // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 96a7b9f451d5b02cc525d53aad46d1ae28dd2a45 Mon Sep 17 00:00:00 2001 From: Ben Date: Sat, 26 Jan 2019 16:08:45 -0500 Subject: [PATCH 088/312] add ITEM_TYPES and misc --- types/react-ultimate-pagination/index.d.ts | 27 ++++++++---- .../react-ultimate-pagination-tests.tsx | 44 ++++++++++++++++++- types/react-ultimate-pagination/tsconfig.json | 1 + 3 files changed, 61 insertions(+), 11 deletions(-) diff --git a/types/react-ultimate-pagination/index.d.ts b/types/react-ultimate-pagination/index.d.ts index 8e2c917d75..cb7b83e4c0 100644 --- a/types/react-ultimate-pagination/index.d.ts +++ b/types/react-ultimate-pagination/index.d.ts @@ -27,36 +27,45 @@ export interface PaginationComponentProps { onClick: () => void; } +export enum ITEM_TYPES { + PAGE = "PAGE", + ELLIPSIS = "ELLIPSIS", + FIRST_PAGE_LINK = "FIRST_PAGE_LINK", + PREVIOUS_PAGE_LINK = "PREVIOUS_PAGE_LINK", + NEXT_PAGE_LINK = "NEXT_PAGE_LINK", + LAST_PAGE_LINK = "LAST_PAGE_LINK", +} + export interface ItemTypeToComponent { /** * A link to a page */ - PAGE: React.ComponentType, + PAGE: React.ComponentType; /** * An item that represents groups of pages that currently are not visible in paginator (can be used to navigate to the page in the group that is the nearest to the current page) */ - ELLIPSIS: React.ComponentType, + ELLIPSIS: React.ComponentType; /** * A link to the first page */ - FIRST_PAGE_LINK: React.ComponentType, + FIRST_PAGE_LINK: React.ComponentType; /** * A link to the previous page */ - PREVIOUS_PAGE_LINK: React.ComponentType, + PREVIOUS_PAGE_LINK: React.ComponentType; /** * A link to the next page */ - NEXT_PAGE_LINK: React.ComponentType, + NEXT_PAGE_LINK: React.ComponentType; /** * A link to the last page */ - LAST_PAGE_LINK: React.ComponentType, + LAST_PAGE_LINK: React.ComponentType; } export interface CreateUltimatePaginationOptions { @@ -66,9 +75,9 @@ export interface CreateUltimatePaginationOptions { itemTypeToComponent: ItemTypeToComponent; /** - * A React.js component that will be used as a wrapper for pagination items + * A React.js component that will be used as a wrapper for pagination items */ - WrapperComponent: string|React.ComponentType; + WrapperComponent?: string|React.ComponentType; } export interface UltimatePaginationProps { @@ -108,7 +117,7 @@ export interface UltimatePaginationProps { hideFirstAndLastPageLinks?: boolean; /** - * Callback that will be called with new page when it should be changed by user interaction + * Callback that will be called with new page when it should be changed by user interaction */ onChange?: (newPage: number) => void; diff --git a/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx index 8116f5e42b..8cebdcbf52 100644 --- a/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx +++ b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx @@ -2,7 +2,8 @@ import * as React from "react"; import { PaginationComponentProps, createUltimatePagination, - ItemTypeToComponent + ItemTypeToComponent, + ITEM_TYPES } from "react-ultimate-pagination"; function Page(props: PaginationComponentProps) { @@ -15,6 +16,12 @@ function Page(props: PaginationComponentProps) { ); } +function PageWithExtraProps(props: PaginationComponentProps & { color: "red" }) { + return ( + + ); +} + function Ellipsis(props: PaginationComponentProps) { return ; } @@ -39,6 +46,7 @@ function Wrapper(props: { children: React.ReactChildren }) { return
    {props.children}
    ; } +// ItemTypeToComponent using strings const itemTypeToComponent: ItemTypeToComponent = { PAGE: Page, ELLIPSIS: Ellipsis, @@ -48,6 +56,38 @@ const itemTypeToComponent: ItemTypeToComponent = { LAST_PAGE_LINK: LastPageLink }; -const UltimatePagination = createUltimatePagination({ itemTypeToComponent, WrapperComponent: Wrapper }); // $ExpectType React.ComponentType +// ItemTypeToComponent using enum +const itemTypeToComponent2: ItemTypeToComponent = { + [ITEM_TYPES.PAGE]: Page, + [ITEM_TYPES.ELLIPSIS]: Ellipsis, + [ITEM_TYPES.FIRST_PAGE_LINK]: FirstPageLink, + [ITEM_TYPES.PREVIOUS_PAGE_LINK]: PreviousPageLink, + [ITEM_TYPES.NEXT_PAGE_LINK]: NextPageLink, + [ITEM_TYPES.LAST_PAGE_LINK]: LastPageLink +}; +// ItemTypeToComponent using Page with extra props +const itemTypeToComponent3: Partial = { + [ITEM_TYPES.PAGE]: PageWithExtraProps, +}; + +const UltimatePagination = createUltimatePagination({ itemTypeToComponent, WrapperComponent: Wrapper }); // $ExpectType ComponentType + +// With required props ; + +// With all props + {}} + siblingPagesRange={99} +/>; + +// With unspported prop +; // $ExpectError diff --git a/types/react-ultimate-pagination/tsconfig.json b/types/react-ultimate-pagination/tsconfig.json index b16cb5d3d0..748045849b 100644 --- a/types/react-ultimate-pagination/tsconfig.json +++ b/types/react-ultimate-pagination/tsconfig.json @@ -8,6 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ "../" From ccd3077c6074b216713f69c7d61a56f5aa7cd99f Mon Sep 17 00:00:00 2001 From: Ben Date: Sat, 26 Jan 2019 16:16:17 -0500 Subject: [PATCH 089/312] allow any props --- types/react-ultimate-pagination/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-ultimate-pagination/index.d.ts b/types/react-ultimate-pagination/index.d.ts index cb7b83e4c0..2f7c26c210 100644 --- a/types/react-ultimate-pagination/index.d.ts +++ b/types/react-ultimate-pagination/index.d.ts @@ -77,7 +77,7 @@ export interface CreateUltimatePaginationOptions { /** * A React.js component that will be used as a wrapper for pagination items */ - WrapperComponent?: string|React.ComponentType; + WrapperComponent?: string|React.ComponentType; } export interface UltimatePaginationProps { From 324fab550d52313b7862f8d1ffc68974cbfc7b56 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 22:38:58 +0100 Subject: [PATCH 090/312] Update index.d.ts --- types/coinbase/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 6731ff3a79..27768610a2 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -547,7 +547,7 @@ export class Account implements Resource { allow_withdrawals: boolean; /** - * Account worth in native balance. + * Account worth in fiat. */ native_balance: MoneyHash; @@ -914,6 +914,11 @@ export class Buy implements Resource { * When a buy isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp */ payout_at?: string; + + /** + * Transaction worth in fiat. + */ + native_balance: MoneyHash; /** * Completes a buy that is created in commit: false state. From 64100c212e1bf27066caea74ac636af66942dd48 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 22:45:47 +0100 Subject: [PATCH 091/312] Update index.d.ts --- types/coinbase/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 27768610a2..e30a049b15 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -914,7 +914,7 @@ export class Buy implements Resource { * When a buy isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp */ payout_at?: string; - + /** * Transaction worth in fiat. */ From 5f07f4ebc9a5f2e135e19359efd83d7b44255fa0 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sat, 26 Jan 2019 22:52:17 +0100 Subject: [PATCH 092/312] Update index.d.ts --- types/coinbase/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index e30a049b15..e92fcef8e7 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -645,7 +645,7 @@ export class Account implements Resource { * Lists buys for an account. * Scope: wallet:buys:read */ - getBuys(cb: (error: Error, result: Buy[]) => void): void; + getBuys(opts: null, cb: (error: Error, result: Buy[]) => void): void; /** * Show an individual buy. From fd90d5b6138bc7617260b1af9ed8ec3dbbf28d7b Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 26 Jan 2019 21:39:56 +0100 Subject: [PATCH 093/312] feat: add type for "rollup-plugin-node-builtins" --- types/rollup-plugin-node-builtins/index.d.ts | 11 +++++++++++ types/rollup-plugin-node-builtins/package.json | 6 ++++++ .../rollup-plugin-node-builtins-tests.ts | 16 ++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 types/rollup-plugin-node-builtins/package.json diff --git a/types/rollup-plugin-node-builtins/index.d.ts b/types/rollup-plugin-node-builtins/index.d.ts index 70f8b3c873..e8506a94ff 100644 --- a/types/rollup-plugin-node-builtins/index.d.ts +++ b/types/rollup-plugin-node-builtins/index.d.ts @@ -2,4 +2,15 @@ // Project: https://github.com/calvinmetcalf/rollup-plugin-node-builtins#readme // Definitions by: Kocal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +import { Plugin } from 'rollup'; + +export interface Options { + crypto?: boolean; + fs?: boolean; +} + +export default function builtins(options?: Options): Plugin; diff --git a/types/rollup-plugin-node-builtins/package.json b/types/rollup-plugin-node-builtins/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-node-builtins/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts b/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts index e69de29bb2..53e488cd00 100644 --- a/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts +++ b/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts @@ -0,0 +1,16 @@ +import builtins from 'rollup-plugin-node-builtins'; + +// No options (default) +(() => { + // $ExpectType Plugin + builtins(); +})(); + +// With `crypto` and `fs` enabled +(() => { + // $ExpectType Plugin + builtins({ + crypto: true, + fs: true, + }); +})(); From 3f944ca274d0eb2404905e1de7d4ba76535074e1 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 08:48:50 +0100 Subject: [PATCH 094/312] chore: setup type --- types/rollup-plugin-node-globals/index.d.ts | 4 ++++ .../rollup-plugin-node-globals-tests.ts | 0 .../rollup-plugin-node-globals/tsconfig.json | 23 +++++++++++++++++++ types/rollup-plugin-node-globals/tslint.json | 1 + 4 files changed, 28 insertions(+) create mode 100644 types/rollup-plugin-node-globals/index.d.ts create mode 100644 types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts create mode 100644 types/rollup-plugin-node-globals/tsconfig.json create mode 100644 types/rollup-plugin-node-globals/tslint.json diff --git a/types/rollup-plugin-node-globals/index.d.ts b/types/rollup-plugin-node-globals/index.d.ts new file mode 100644 index 0000000000..08b8b52926 --- /dev/null +++ b/types/rollup-plugin-node-globals/index.d.ts @@ -0,0 +1,4 @@ +// Type definitions for rollup-plugin-node-globals 1.4 +// Project: https://github.com/calvinmetcalf/rollup-plugin-node-globals#readme +// Definitions by: Kocal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts b/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/rollup-plugin-node-globals/tsconfig.json b/types/rollup-plugin-node-globals/tsconfig.json new file mode 100644 index 0000000000..29e93758c9 --- /dev/null +++ b/types/rollup-plugin-node-globals/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", + "rollup-plugin-node-globals-tests.ts" + ] +} diff --git a/types/rollup-plugin-node-globals/tslint.json b/types/rollup-plugin-node-globals/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-node-globals/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 69863b59ba6fd60ee321582d883677d468b4d74e Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 09:23:25 +0100 Subject: [PATCH 095/312] feat: add type for "rollup-plugin-node-globals" --- types/rollup-plugin-node-globals/index.d.ts | 24 +++++++++++ types/rollup-plugin-node-globals/package.json | 6 +++ .../rollup-plugin-node-globals-tests.ts | 43 +++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 types/rollup-plugin-node-globals/package.json diff --git a/types/rollup-plugin-node-globals/index.d.ts b/types/rollup-plugin-node-globals/index.d.ts index 08b8b52926..97284aaabd 100644 --- a/types/rollup-plugin-node-globals/index.d.ts +++ b/types/rollup-plugin-node-globals/index.d.ts @@ -2,3 +2,27 @@ // Project: https://github.com/calvinmetcalf/rollup-plugin-node-globals#readme // Definitions by: Kocal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Plugin } from 'rollup'; + +export interface Options { + // Every files will be parsed by default, but you can specify which files to include or exclude + include?: Array | string | RegExp | null; + exclude?: Array | string | RegExp | null; + + // Enable sourcemaps support + sourceMap ?: boolean; + + // Plugin's options + process?: boolean; + global?: boolean; + buffer?: boolean; + dirname?: boolean; + filename?: boolean; + baseDir?: string; +} + +export default function globals(options?: Options): Plugin; diff --git a/types/rollup-plugin-node-globals/package.json b/types/rollup-plugin-node-globals/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-node-globals/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts b/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts index e69de29bb2..93d10a2730 100644 --- a/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts +++ b/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts @@ -0,0 +1,43 @@ +import globals from 'rollup-plugin-node-globals'; + +// No options (default) +(() => { + // $ExpectType Plugin + globals(); +})(); + +// With every options +(() => { + // $ExpectType Plugin + globals({ + process: false, + global: false, + buffer: false, + dirname: false, + filename: false, + baseDir: '/', + }); +})(); + +// Filter files +(() => { + // $ExpectType Plugin + globals({ + include: '*.js', + exclude: '*.js', + }); + + // $ExpectType Plugin + globals({ + include: /.js$/, + exclude: ['foo.js', 'bar.js'], + }); +})(); + +// Sourcemaps +(() => { + // $ExpectType Plugin + globals({ + sourceMap: false, + }); +})(); From ef068528b46455cfb2c28c164e2db7b913e3b8d8 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 10:09:58 +0100 Subject: [PATCH 096/312] feat: add typings for defaults-deep --- types/defaults-deep/defaults-deep-tests.ts | 7 +++++++ types/defaults-deep/index.d.ts | 10 ++++++++++ types/defaults-deep/tsconfig.json | 23 ++++++++++++++++++++++ types/defaults-deep/tslint.json | 1 + 4 files changed, 41 insertions(+) create mode 100644 types/defaults-deep/defaults-deep-tests.ts create mode 100644 types/defaults-deep/index.d.ts create mode 100644 types/defaults-deep/tsconfig.json create mode 100644 types/defaults-deep/tslint.json diff --git a/types/defaults-deep/defaults-deep-tests.ts b/types/defaults-deep/defaults-deep-tests.ts new file mode 100644 index 0000000000..826bbb4d0f --- /dev/null +++ b/types/defaults-deep/defaults-deep-tests.ts @@ -0,0 +1,7 @@ +import defaults from 'defaults-deep'; + +defaults(); +defaults({a: 'foo'}); +defaults({a: 'foo'}, {a: 'bar'}); +defaults({a: 'foo'}, {a: 'bar'}, {a: 'foobar'}); +defaults({a: {b: 'foo'}}, {a: {b: 'bar'}}); diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts new file mode 100644 index 0000000000..cc96e2bcad --- /dev/null +++ b/types/defaults-deep/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for defaults-deep 0.2 +// Project: https://github.com/jonschlinkert/defaults-deep +// Definitions by: Kocal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Obj { + [k: string]: any; +} + +export default function defaultDeep(obj?: Obj, ...objs: Obj[]): Obj; diff --git a/types/defaults-deep/tsconfig.json b/types/defaults-deep/tsconfig.json new file mode 100644 index 0000000000..9b7c12bf2b --- /dev/null +++ b/types/defaults-deep/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", + "defaults-deep-tests.ts" + ] +} diff --git a/types/defaults-deep/tslint.json b/types/defaults-deep/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defaults-deep/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6aa5a8d5f3d81b8bfa9fa0adb3995590eadf8c53 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 10:24:45 +0100 Subject: [PATCH 097/312] fix: shut down "strict-export-declare-modifiers" rule --- types/defaults-deep/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts index cc96e2bcad..74543fc677 100644 --- a/types/defaults-deep/index.d.ts +++ b/types/defaults-deep/index.d.ts @@ -8,3 +8,6 @@ interface Obj { } export default function defaultDeep(obj?: Obj, ...objs: Obj[]): Obj; + +// strict-export-declare-modifiers +export {}; From 5b4074d724687ec45fde17a7df405cc1c9c54bd2 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 11:59:55 +0100 Subject: [PATCH 098/312] chore: use my name --- types/defaults-deep/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts index 74543fc677..b7583dd92e 100644 --- a/types/defaults-deep/index.d.ts +++ b/types/defaults-deep/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for defaults-deep 0.2 // Project: https://github.com/jonschlinkert/defaults-deep -// Definitions by: Kocal +// Definitions by: Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Obj { From ce8bddf8b0cb96a2d070b9816a4edf6e696c938d Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 12:00:26 +0100 Subject: [PATCH 099/312] chore: use my name --- types/rollup-plugin-node-builtins/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/rollup-plugin-node-builtins/index.d.ts b/types/rollup-plugin-node-builtins/index.d.ts index e8506a94ff..e839485ac9 100644 --- a/types/rollup-plugin-node-builtins/index.d.ts +++ b/types/rollup-plugin-node-builtins/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for rollup-plugin-node-builtins 2.1 // Project: https://github.com/calvinmetcalf/rollup-plugin-node-builtins#readme -// Definitions by: Kocal +// Definitions by: Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From a3ce51ce058fe7d35f7e507af91184bc7e09c0ce Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 12:00:53 +0100 Subject: [PATCH 100/312] chore: use my name --- types/rollup-plugin-node-globals/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/rollup-plugin-node-globals/index.d.ts b/types/rollup-plugin-node-globals/index.d.ts index 97284aaabd..2cf29ae912 100644 --- a/types/rollup-plugin-node-globals/index.d.ts +++ b/types/rollup-plugin-node-globals/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for rollup-plugin-node-globals 1.4 // Project: https://github.com/calvinmetcalf/rollup-plugin-node-globals#readme -// Definitions by: Kocal +// Definitions by: Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From 54ff498709b81ecac06d6842057ae3512939e8f7 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 27 Jan 2019 12:01:38 +0100 Subject: [PATCH 101/312] chore: use my name --- types/buble/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/buble/index.d.ts b/types/buble/index.d.ts index af2a7e26ee..db3cb0a7b7 100644 --- a/types/buble/index.d.ts +++ b/types/buble/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for buble 0.19 // Project: https://github.com/Rich-Harris/buble#README -// Definitions by: Kocal +// Definitions by: Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 From 966470e9e5f06e80625a2fa6d89ec1663aed7efd Mon Sep 17 00:00:00 2001 From: Denis Cappellin Date: Sun, 27 Jan 2019 12:10:10 +0100 Subject: [PATCH 102/312] Add missing definition for writeLong --- types/bytebuffer/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index bafed6edf8..eaa1a509d5 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -127,7 +127,7 @@ declare class ByteBuffer * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. */ static calculateUTF8Chars( str: string ): number; - + /** * Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes. */ @@ -574,6 +574,11 @@ declare class ByteBuffer */ writeInt8( value: number, offset?: number ): ByteBuffer; + /** + * Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64. + */ + writeLong( value: number | Long, offset?: number ): ByteBuffer; + /** * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. */ From 4b7179c7134ad7c68fb3e24606f02e0fad53d582 Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Sun, 27 Jan 2019 15:32:37 +0200 Subject: [PATCH 103/312] Add more specific typing for mapboxgl expressions List taken from https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions --- types/mapbox-gl/index.d.ts | 34 +++++++++++++++++++++++++++--- types/mapbox-gl/mapbox-gl-tests.ts | 11 ++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 149d433a89..e47db488ae 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,8 +1,10 @@ // Type definitions for Mapbox GL JS v0.51.0 // Project: https://github.com/mapbox/mapbox-gl-js -// Definitions by: Dominik Bruderer , Patrick Reames +// Definitions by: Dominik Bruderer +// Patrick Reames +// Karl-Aksel Puulmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// @@ -20,7 +22,33 @@ declare namespace mapboxgl { type LngLatLike = LngLat | { lng: number; lat: number; } | { lon: number; lat: number; } | [number, number]; type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number]; type PointLike = Point | [number, number]; - type Expression = any[]; + + type ExpressionName = + // Types + | 'array' | 'boolean' | 'collator' | 'format' | 'literal' | 'number' | 'object' | 'string' + | 'to-boolean' | 'to-color' | 'to-number' | 'to-string' | 'typeof' + // Feature data + | 'feature-state' | 'geometry-type' | 'id' | 'line-progress' | 'properties' + // Lookup + | 'at' | 'get' | 'has' | 'length' + // Decision + | '!=' | '<' | '<=' | '==' | '>' | '>=' | 'all' | 'any' | 'case' | 'match' + // Ramps, scales, curves + | 'interpolate' | 'interpolate-hcl' | 'interpolate-lab' | 'step' + // Variable binding + | 'let' | 'var' + // String + | 'concat' | 'downcase' | 'is-supported-script' | 'resolved-locale' | 'upcase' + // Color + | 'rgb' | 'rgba' + // Math + | '-' | '*' | '/' | '%' | '^' | '+' | 'abs' | 'acos' | 'asin' | 'atan' | 'ceil' | 'cos' | 'e' + | 'floor' | 'ln' | 'ln2' | 'log10' | 'log2' | 'max' | 'min' | 'pi' | 'round' | 'sin' | 'sqrt' | 'tan' + // Zoom, Heatmap + | 'zoom' | 'heatmap-density'; + + type Expression = [ExpressionName, ...any[]] + type Anchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index d119c76bd5..e5ad6663b1 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -788,3 +788,14 @@ expectType(map.on('touchcancel', 'text', (ev) => { expectType(ev); expectType(ev.features); })); + +/* + * Expression + */ +expectType(['id']); +expectType(['get', 'property']); +expectType([ + 'format', + ['concat', ['get', 'name'], '\n'], {}, + ['concat', ['get', 'area'], 'foobar', { 'font-scale': 0.8 }] +]); From b490c27a7addaf7c06100d5595da81638309ce9b Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Sun, 27 Jan 2019 15:38:14 +0200 Subject: [PATCH 104/312] Allow text-field, allow-icon-overlap to be an expression https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-text-field --- types/mapbox-gl/index.d.ts | 4 ++-- types/mapbox-gl/mapbox-gl-tests.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index e47db488ae..bfc25ee535 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1389,7 +1389,7 @@ declare namespace mapboxgl { 'symbol-spacing'?: number | Expression; 'symbol-avoid-edges'?: boolean; 'symbol-z-order'?: 'viewport-y' | 'source'; - 'icon-allow-overlap'?: boolean | StyleFunction; + 'icon-allow-overlap'?: boolean | StyleFunction | Expression; 'icon-ignore-placement'?: boolean; 'icon-optional'?: boolean; 'icon-rotation-alignment'?: 'map' | 'viewport' | 'auto'; @@ -1405,7 +1405,7 @@ declare namespace mapboxgl { 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; - 'text-field'?: string | StyleFunction; + 'text-field'?: string | StyleFunction | Expression; 'text-font'?: string | string[]; 'text-size'?: number | StyleFunction | Expression; 'text-max-width'?: number | Expression; diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index e5ad6663b1..92f0c6c7c7 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -50,7 +50,8 @@ map.on('load', function(){ "type": "symbol", "source": "data", "layout": { - "icon-image": "marker-15" + "icon-image": "marker-15", + "text-field": ['get', 'property'] } }); From 097c5761ab284480513ebbc9be22a3c77367e1bc Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Sun, 27 Jan 2019 15:59:43 +0200 Subject: [PATCH 105/312] More accurately type Style.sources --- types/mapbox-gl/index.d.ts | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index bfc25ee535..786b7260b6 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -101,7 +101,7 @@ declare namespace mapboxgl { isStyleLoaded(): boolean; - addSource(id: string, source: VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + addSource(id: string, source: AnySourceData): this; isSourceLoaded(id: string): boolean; @@ -109,7 +109,7 @@ declare namespace mapboxgl { removeSource(id: string): this; - getSource(id: string): VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource; + getSource(id: string): AnySourceImpl; addImage(name: string, image: HTMLImageElement | ArrayBufferView | { width: number, height: number, data: Uint8Array | Uint8ClampedArray } | ImageData, options?: { pixelRatio?: number, sdf?: boolean }): this; @@ -654,7 +654,7 @@ declare namespace mapboxgl { name?: string; pitch?: number; light?: Light; - sources?: any; + sources?: Sources; sprite?: string; transition?: Transition; version: number; @@ -676,6 +676,14 @@ declare namespace mapboxgl { 'intensity-transition'?: Transition; } + export interface Sources { + [sourceName: string]: AnySourceData; + } + + export type AnySourceData = GeoJSONSourceRaw | VideoSourceRaw | ImageSourceRaw | CanvasSourceRaw | VectorSource | RasterSource | RasterDemSource + + export type AnySourceImpl = GeoJSONSource | VideoSource | ImageSource | CanvasSource | VectorSource | RasterSource | RasterDemSource + export interface Source { type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } @@ -727,10 +735,11 @@ declare namespace mapboxgl { /** * VideoSource */ - export interface VideoSource extends VideoSourceOptions { + export interface VideoSourceRaw extends Source, VideoSourceOptions { + type: 'video'; } - export class VideoSource implements Source { + export class VideoSource implements VideoSourceRaw { type: 'video'; constructor(options?: mapboxgl.VideoSourceOptions); @@ -749,10 +758,11 @@ declare namespace mapboxgl { /** * ImageSource */ - export interface ImageSource extends ImageSourceOptions { + export interface ImageSourceRaw extends Source, ImageSourceOptions { + type: 'image'; } - export class ImageSource implements Source { + export class ImageSource implements ImageSourceRaw { type: 'image'; constructor(options?: mapboxgl.ImageSourceOptions); @@ -769,7 +779,11 @@ declare namespace mapboxgl { /** * CanvasSource */ - export class CanvasSource implements Source, CanvasSourceOptions { + export interface CanvasSourceRaw extends Source, CanvasSourceOptions { + type: 'canvas'; + } + + export class CanvasSource implements CanvasSourceRaw { type: 'canvas'; coordinates: number[][]; @@ -1274,7 +1288,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string | VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + source?: string | AnySourceData; 'source-layer'?: string; From 74358036963562bbdc12c13a14efe327bec88354 Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Sun, 27 Jan 2019 16:16:05 +0200 Subject: [PATCH 106/312] Dump typescript version in react-map-gl This is needed to update mapbox-gl types. --- types/react-map-gl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 772e24081f..4d147d3611 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert Imig // Fabio Berta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import * as React from 'react'; import * as MapboxGL from 'mapbox-gl'; From 5a05abfba06b5a64de3b0de770f28aa02c793cd4 Mon Sep 17 00:00:00 2001 From: Dolan Miu Date: Sun, 27 Jan 2019 17:47:55 +0000 Subject: [PATCH 107/312] Export RepositoryInitOptions --- types/nodegit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/nodegit/index.d.ts b/types/nodegit/index.d.ts index d1afcd6ea4..704ff9b037 100644 --- a/types/nodegit/index.d.ts +++ b/types/nodegit/index.d.ts @@ -79,7 +79,7 @@ export { Refspec } from './ref-spec'; export { Reference } from './reference'; export { RemoteCallbacks } from './remote-callbacks'; export { Remote } from './remote'; -export { Repository } from './repository'; +export { Repository, RepositoryInitOptions } from './repository'; export { Reset } from './reset'; export { Revparse } from './rev-parse'; export { Revwalk } from './rev-walk'; From 7f27ae1f9169cdf2225fb89466d44cbaa1f6cf88 Mon Sep 17 00:00:00 2001 From: Dolan Miu Date: Sun, 27 Jan 2019 17:49:49 +0000 Subject: [PATCH 108/312] Version bump --- types/nodegit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/nodegit/index.d.ts b/types/nodegit/index.d.ts index 704ff9b037..680aec7174 100644 --- a/types/nodegit/index.d.ts +++ b/types/nodegit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for nodegit 0.22 +// Type definitions for nodegit 0.24 // Project: https://github.com/nodegit/nodegit // Definitions by: Dolan Miu , Tobias Nießen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From f55a8706f0309b3add7e8ce3f8505ce953c53de7 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Sun, 27 Jan 2019 19:52:15 +0100 Subject: [PATCH 109/312] Update index.d.ts --- types/coinbase/index.d.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index e92fcef8e7..5f9f8682f0 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -898,7 +898,7 @@ export class Buy implements Resource { /** * Fee associated to this buy */ - fee: MoneyHash; + fees: Fee[]; /** * Has this buy been committed? @@ -915,10 +915,13 @@ export class Buy implements Resource { */ payout_at?: string; - /** - * Transaction worth in fiat. - */ - native_balance: MoneyHash; + unit_price: UnitPrice; + + hold_business_days: number; + + is_first_buy: boolean; + + requires_completion_step: boolean; /** * Completes a buy that is created in commit: false state. @@ -930,6 +933,17 @@ export class Buy implements Resource { commit(cb: (error: Error, transaction: Buy) => void): void; } +export interface Fee { + amount: string; + type: string; +} + +export interface UnitPrice { + amount: string; + currency: string; + scale: number; +} + export type SellStatus = "created" | "completed" | "canceled"; /** From f8ce3b3f9fc26484f43dbf85a311788ed7a7f364 Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:11:52 -0500 Subject: [PATCH 110/312] Added type definitions for dlv --- types/dlv/dlv-tests.ts | 44 +++++++++++++++++++++++++++++++++++++++++ types/dlv/index.d.ts | 22 +++++++++++++++++++++ types/dlv/tsconfig.json | 23 +++++++++++++++++++++ types/dlv/tslint.json | 3 +++ 4 files changed, 92 insertions(+) create mode 100644 types/dlv/dlv-tests.ts create mode 100644 types/dlv/index.d.ts create mode 100644 types/dlv/tsconfig.json create mode 100644 types/dlv/tslint.json diff --git a/types/dlv/dlv-tests.ts b/types/dlv/dlv-tests.ts new file mode 100644 index 0000000000..abe4b259c3 --- /dev/null +++ b/types/dlv/dlv-tests.ts @@ -0,0 +1,44 @@ +import dlv from 'dlv'; + +const obj = { + undef: undefined, + zero: 0, + one: 1, + n: null, + f: false, + a: { + two: 2, + b: { + three: 3, + c: { + four: 4 + } + } + } +}; + +// Test without defaults +dlv(obj, ''); +dlv(obj, 'one'); +dlv(obj, 'one.two'); +dlv(obj, 'a'); +dlv(obj, 'a.two'); +dlv(obj, 'a.b'); +dlv(obj, 'a.b.three'); +dlv(obj, 'a.b.c'); +dlv(obj, 'a.b.c.four'); +dlv(obj, 'n'); +dlv(obj, 'n.badkey'); +dlv(obj, 'f'); +dlv(obj, 'f.badkey'); + +// Test defaults +dlv(obj, '', 'foo'); +dlv(obj, 'undef', 'foo'); +dlv(obj, 'n', null); +dlv(obj, 'n.badkey', 'foo'); +dlv(obj, 'zero', 0); +dlv(obj, 'a.badkey', 'foo'); +dlv(obj, 'a.badkey.anotherbadkey', 'foo'); +dlv(obj, 'f', false); +dlv(obj, 'f.badkey', 'foo'); diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts new file mode 100644 index 0000000000..ef84668e7d --- /dev/null +++ b/types/dlv/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for dlv 1.1.2 +// Project: https://github.com/developit/dlv +// Definitions by: Ryan Sonshine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +declare module 'dlv' { + /** + * Safely get a dot-notated path within a nested object, with ability to + * return a default if the full key path does not exist or the value is + * undefined + * + * @param {object} object Object to look up the key on + * @param {(string | string[])} key Key in dot notation to lookup. Can also be an array key. + * @param {T} [defaultValue] Default value to return if the full key path does not exist on the object + * @returns {(any | T))} Value if found in path, the default if not found, undefined if no default provided + */ + export default function dlv( + object : object, + key : string | string[], + defaultValue?: T, + ): any | T; +} diff --git a/types/dlv/tsconfig.json b/types/dlv/tsconfig.json new file mode 100644 index 0000000000..ab250de319 --- /dev/null +++ b/types/dlv/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", + "dlv-tests.ts" + ] +} diff --git a/types/dlv/tslint.json b/types/dlv/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/dlv/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 5afbc6c1d6d3b897f666a937bbad0a5459de328a Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:22:52 -0500 Subject: [PATCH 111/312] Fixes union type for dlv return type --- types/dlv/index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts index ef84668e7d..845710e524 100644 --- a/types/dlv/index.d.ts +++ b/types/dlv/index.d.ts @@ -11,12 +11,12 @@ declare module 'dlv' { * * @param {object} object Object to look up the key on * @param {(string | string[])} key Key in dot notation to lookup. Can also be an array key. - * @param {T} [defaultValue] Default value to return if the full key path does not exist on the object - * @returns {(any | T))} Value if found in path, the default if not found, undefined if no default provided + * @param {any} [defaultValue] Default value to return if the full key path does not exist on the object + * @returns {any} Value if found in path, the default if not found, undefined if no default provided */ - export default function dlv( + export default function dlv( object : object, key : string | string[], - defaultValue?: T, - ): any | T; + defaultValue?: any, + ): any; } From 3b7700e7531121e45645d1bce9b19cba2af7eddb Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:33:54 -0500 Subject: [PATCH 112/312] Uses dts-gen to set up module structure --- types/dlv/index.d.ts | 34 ++++++++++++++-------------------- types/dlv/tsconfig.json | 1 - types/dlv/tslint.json | 4 +--- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts index 845710e524..b8f2608fe9 100644 --- a/types/dlv/index.d.ts +++ b/types/dlv/index.d.ts @@ -1,22 +1,16 @@ -// Type definitions for dlv 1.1.2 -// Project: https://github.com/developit/dlv +// Type definitions for dlv 1.1 +// Project: https://github.com/developit/dlv#readme // Definitions by: Ryan Sonshine // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 -declare module 'dlv' { - /** - * Safely get a dot-notated path within a nested object, with ability to - * return a default if the full key path does not exist or the value is - * undefined - * - * @param {object} object Object to look up the key on - * @param {(string | string[])} key Key in dot notation to lookup. Can also be an array key. - * @param {any} [defaultValue] Default value to return if the full key path does not exist on the object - * @returns {any} Value if found in path, the default if not found, undefined if no default provided - */ - export default function dlv( - object : object, - key : string | string[], - defaultValue?: any, - ): any; -} + +/** + * Safely get a dot-notated path within a nested object, with ability to + * return a default if the full key path does not exist or the value is + * undefined + * + * @param {object} object Object to look up the key on + * @param {(string | string[])} key Key in dot notation to lookup. Can also be an array key. + * @param {any} [defaultValue] Default value to return if the full key path does not exist on the object + * @returns {any} Value if found in path, the default if not found, undefined if no default provided +*/ +export default function dlv(object: object, key: string | string[], defaultValue?: any): any; diff --git a/types/dlv/tsconfig.json b/types/dlv/tsconfig.json index ab250de319..34d76ae224 100644 --- a/types/dlv/tsconfig.json +++ b/types/dlv/tsconfig.json @@ -7,7 +7,6 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/dlv/tslint.json b/types/dlv/tslint.json index f93cf8562a..3db14f85ea 100644 --- a/types/dlv/tslint.json +++ b/types/dlv/tslint.json @@ -1,3 +1 @@ -{ - "extends": "dtslint/dt.json" -} +{ "extends": "dtslint/dt.json" } From 36a2c05baab019858e42444c26eb37d402b58de7 Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:40:51 -0500 Subject: [PATCH 113/312] Adds strictFunctionTypes to tsconfig --- types/dlv/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/dlv/tsconfig.json b/types/dlv/tsconfig.json index 34d76ae224..222ce070e7 100644 --- a/types/dlv/tsconfig.json +++ b/types/dlv/tsconfig.json @@ -13,7 +13,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true }, "files": [ "index.d.ts", From 6025289427c09bc854ceebd6a83dbf9eca474a61 Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:44:42 -0500 Subject: [PATCH 114/312] Adds typescript version to type definition file --- types/dlv/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts index b8f2608fe9..3d86aa91b5 100644 --- a/types/dlv/index.d.ts +++ b/types/dlv/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/developit/dlv#readme // Definitions by: Ryan Sonshine // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /** * Safely get a dot-notated path within a nested object, with ability to From 73f13bed814d26fdd051a945022959ef81fb8b04 Mon Sep 17 00:00:00 2001 From: Ryan Sonshine Date: Sun, 27 Jan 2019 14:54:17 -0500 Subject: [PATCH 115/312] Removes docstring from dlv type definition --- types/dlv/index.d.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts index 3d86aa91b5..5813ec0595 100644 --- a/types/dlv/index.d.ts +++ b/types/dlv/index.d.ts @@ -8,10 +8,5 @@ * Safely get a dot-notated path within a nested object, with ability to * return a default if the full key path does not exist or the value is * undefined - * - * @param {object} object Object to look up the key on - * @param {(string | string[])} key Key in dot notation to lookup. Can also be an array key. - * @param {any} [defaultValue] Default value to return if the full key path does not exist on the object - * @returns {any} Value if found in path, the default if not found, undefined if no default provided -*/ + */ export default function dlv(object: object, key: string | string[], defaultValue?: any): any; From a8a2b4f1c11351c5cc7ff48cc13d709f64e838ec Mon Sep 17 00:00:00 2001 From: Dave Cardwell Date: Sun, 27 Jan 2019 17:32:20 -0500 Subject: [PATCH 116/312] [script-ext-html-webpack-plugin] Add initial types --- .../script-ext-html-webpack-plugin/index.d.ts | 79 ++++++++++++ .../script-ext-html-webpack-plugin-tests.ts | 112 ++++++++++++++++++ .../tsconfig.json | 16 +++ .../tslint.json | 1 + 4 files changed, 208 insertions(+) create mode 100644 types/script-ext-html-webpack-plugin/index.d.ts create mode 100644 types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts create mode 100644 types/script-ext-html-webpack-plugin/tsconfig.json create mode 100644 types/script-ext-html-webpack-plugin/tslint.json diff --git a/types/script-ext-html-webpack-plugin/index.d.ts b/types/script-ext-html-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..636ac550e5 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for script-ext-html-webpack-plugin 2.1 +// Project: https://github.com/numical/script-ext-html-webpack-plugin +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from "webpack"; + +export = ScriptExtHtmlWebpackPlugin; + +declare class ScriptExtHtmlWebpackPlugin extends Plugin { + constructor(options?: ScriptExtHtmlWebpackPlugin.Options); +} + +type ScriptMatchingPatternBase = + | string + | RegExp + | ReadonlyArray; + +interface ScriptMatchingPatternHash { + test: ScriptMatchingPatternBase; +} + +type ScriptMatchingPattern = + | ScriptMatchingPatternBase + | ScriptMatchingPatternHash; + +type ScriptMatchingPatternPre = + | ScriptMatchingPatternBase + | ScriptMatchingPatternHash & { + chunks?: "initial" | "async" | "all"; + }; + +interface Custom { + test: ScriptMatchingPattern; + attribute: string; + value?: string; +} + +declare namespace ScriptExtHtmlWebpackPlugin { + interface Options { + /** + * scripts that should be inlined in the html (default: `[]`) + */ + inline?: ScriptMatchingPattern; + /** + * script names that should have no attribute (default: `[]`) + */ + sync?: ScriptMatchingPattern; + /** + * script names that should have an async attribute (default: `[]`) + */ + async?: ScriptMatchingPattern; + /** + * script names that should have a defer attribute (default: `[]`) + */ + defer?: ScriptMatchingPattern; + /** + * the default attribute to set - 'sync' actually results in no attribute (default: 'sync') + */ + defaultAttribute?: "sync" | "async" | "defer"; + /** + * script names that should have a type="module" attribute (default: `[]`) + */ + module?: ScriptMatchingPattern; + /** + * scripts that should have accompanying preload resource hints (default: `[]`) + */ + preload?: ScriptMatchingPatternPre; + /** + * scripts that should have accompanying prefetch resource hints (default: `[]`) + */ + prefetch?: ScriptMatchingPatternPre; + /** + * scripts that should have a custom attribute(s) added, the attribute(s), and the value(s) + */ + custom?: Custom | Custom[]; + } +} diff --git a/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts b/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts new file mode 100644 index 0000000000..84c42b2ae9 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts @@ -0,0 +1,112 @@ +import ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin"); + +new ScriptExtHtmlWebpackPlugin(); +new ScriptExtHtmlWebpackPlugin({}); + +new ScriptExtHtmlWebpackPlugin({ + inline: "string", + sync: "string", + async: "string", + defer: "string", + module: "string", + preload: "string", + prefetch: "string" +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: ["array"], + sync: ["array"], + async: ["array"], + defer: ["array"], + module: ["array"], + preload: ["array"], + prefetch: ["array"] +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: /regexp/, + sync: /regexp/, + async: /regexp/, + defer: /regexp/, + module: /regexp/, + preload: /regexp/, + prefetch: /regexp/ +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: "string" }, + sync: { test: "string" }, + async: { test: "string" }, + defer: { test: "string" }, + module: { test: "string" }, + preload: { test: "string" }, + prefetch: { test: "string" } +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: ["array"] }, + sync: { test: ["array"] }, + async: { test: ["array"] }, + defer: { test: ["array"] }, + module: { test: ["array"] }, + preload: { test: ["array"] }, + prefetch: { test: ["array"] } +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: /regexp/ }, + sync: { test: /regexp/ }, + async: { test: /regexp/ }, + defer: { test: /regexp/ }, + module: { test: /regexp/ }, + preload: { test: /regexp/ }, + prefetch: { test: /regexp/ } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "initial" }, + prefetch: { test: "string", chunks: "initial" } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "async" }, + prefetch: { test: "string", chunks: "async" } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "all" }, + prefetch: { test: "string", chunks: "all" } +}); + +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "sync" }); +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "async" }); +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "defer" }); + +new ScriptExtHtmlWebpackPlugin({ + custom: { + test: "string", + attribute: "string" + } +}); + +new ScriptExtHtmlWebpackPlugin({ + custom: { + test: ["array"], + attribute: "string", + value: "string" + } +}); + +new ScriptExtHtmlWebpackPlugin({ + custom: [ + { + test: /regexp/, + attribute: "string" + }, + { + test: "string", + attribute: "string", + value: "string" + } + ] +}); diff --git a/types/script-ext-html-webpack-plugin/tsconfig.json b/types/script-ext-html-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..32c8e618e3 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/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", "script-ext-html-webpack-plugin-tests.ts"] +} diff --git a/types/script-ext-html-webpack-plugin/tslint.json b/types/script-ext-html-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/script-ext-html-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e8f50e4c45ac23b9a80ba2b0eb2a526ff70b0116 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 27 Jan 2019 23:52:41 +0100 Subject: [PATCH 117/312] [http-cache-semantics] Add types --- .../http-cache-semantics-tests.ts | 19 ++ types/http-cache-semantics/index.d.ts | 170 ++++++++++++++++++ types/http-cache-semantics/tsconfig.json | 23 +++ types/http-cache-semantics/tslint.json | 1 + 4 files changed, 213 insertions(+) create mode 100644 types/http-cache-semantics/http-cache-semantics-tests.ts create mode 100644 types/http-cache-semantics/index.d.ts create mode 100644 types/http-cache-semantics/tsconfig.json create mode 100644 types/http-cache-semantics/tslint.json diff --git a/types/http-cache-semantics/http-cache-semantics-tests.ts b/types/http-cache-semantics/http-cache-semantics-tests.ts new file mode 100644 index 0000000000..73de43b370 --- /dev/null +++ b/types/http-cache-semantics/http-cache-semantics-tests.ts @@ -0,0 +1,19 @@ +const req = { url: 'https://foo.bar', method: 'GET', headers: { foo: 'bar' } }; +const res = { status: 200, headers: { foo: 'bar' } }; + +import CachePolicy = require('http-cache-semantics'); + +const policy = new CachePolicy(req, res); +new CachePolicy(req, res, { shared: true }); +new CachePolicy(req, res, { cacheHeuristic: 0.1 }); +new CachePolicy(req, res, { immutableMinTimeToLive: 24 * 3600 * 1000 }); +new CachePolicy(req, res, { ignoreCargoCult: false }); +new CachePolicy(req, res, { trustServerDate: true }); + +policy.storable(); // $ExpectType boolean +policy.satisfiesWithoutRevalidation(req); // $ExpectType boolean +policy.responseHeaders(); // $ExpectType Headers +policy.timeToLive(); // $ExpectType number +CachePolicy.fromObject(policy.toObject()); // $ExpectType CachePolicy +policy.revalidationHeaders(req); // $ExpectType Headers +policy.revalidatedPolicy(req, res); // $ExpectType RevalidationPolicy diff --git a/types/http-cache-semantics/index.d.ts b/types/http-cache-semantics/index.d.ts new file mode 100644 index 0000000000..40545f3e0a --- /dev/null +++ b/types/http-cache-semantics/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for http-cache-semantics 4.0 +// Project: https://github.com/kornelski/http-cache-semantics#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = CachePolicy; + +declare class CachePolicy { + constructor(req: CachePolicy.Request, res: CachePolicy.Response, options?: CachePolicy.Options); + + /** + * Returns `true` if the response can be stored in a cache. + * If it's `false` then you MUST NOT store either the request or the response. + */ + storable(): boolean; + + /** + * This is the most important method. Use this method to check whether the cached response is still fresh + * in the context of the new request. + * + * If it returns `true`, then the given `request` matches the original response this cache policy has been + * created with, and the response can be reused without contacting the server. Note that the old response + * can't be returned without being updated, see `responseHeaders()`. + * + * If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), + * or may require to be refreshed first (see `revalidationHeaders()`). + */ + satisfiesWithoutRevalidation(newRequest: CachePolicy.Request): boolean; + + /** + * Returns updated, filtered set of response headers to return to clients receiving the cached response. + * This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) + * and update response's `Age` to avoid doubling cache time. + * + * @example + * cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); + */ + responseHeaders(): CachePolicy.Headers; + + /** + * Returns approximate time in milliseconds until the response becomes stale (i.e. not fresh). + * + * After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, + * there are exceptions, e.g. a client can explicitly allow stale responses, so always check with + * `satisfiesWithoutRevalidation()`. + */ + timeToLive(): number; + + /** + * Chances are you'll want to store the `CachePolicy` object along with the cached response. + * `obj = policy.toObject()` gives a plain JSON-serializable object. + */ + toObject(): CachePolicy.CachePolicyObject; + + /** + * `policy = CachePolicy.fromObject(obj)` creates an instance from object created by `toObject()`. + */ + static fromObject(obj: CachePolicy.CachePolicyObject): CachePolicy; + + /** + * Returns updated, filtered set of request headers to send to the origin server to check if the cached + * response can be reused. These headers allow the origin server to return status 304 indicating the + * response is still fresh. All headers unrelated to caching are passed through as-is. + * + * Use this method when updating cache from the origin server. + * + * @example + * updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); + */ + revalidationHeaders(newRequest: CachePolicy.Request): CachePolicy.Headers; + + /** + * Use this method to update the cache after receiving a new response from the origin server. + */ + revalidatedPolicy( + revalidationRequest: CachePolicy.Request, + revalidationResponse: CachePolicy.Response + ): CachePolicy.RevalidationPolicy; +} + +declare namespace CachePolicy { + interface Request { + url?: string; + method?: string; + headers: Headers; + } + + interface Response { + status?: number; + headers: Headers; + } + + interface Options { + /** + * If `true`, then the response is evaluated from a perspective of a shared cache (i.e. `private` is not + * cacheable and `s-maxage` is respected). If `false`, then the response is evaluated from a perspective + * of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). + * `true` is recommended for HTTP clients. + * @default true + */ + shared?: boolean; + /** + * A fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), + * e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. + * @default 0.1 + */ + cacheHeuristic?: number; + /** + * A number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. + * Note that [per RFC](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension) + * these can become stale, so `max-age` still overrides the default. + * @default 24*3600*1000 (24h) + */ + immutableMinTimeToLive?: number; + /** + * If `true`, common anti-cache directives will be completely ignored if the non-standard `pre-check` + * and `post-check` directives are present. These two useless directives are most commonly found + * in bad StackOverflow answers and PHP's "session limiter" defaults. + * @default false + */ + ignoreCargoCult?: boolean; + /** + * If `false`, then server's `Date` header won't be used as the base for `max-age`. This is against the RFC, + * but it's useful if you want to cache responses with very short `max-age`, but your local clock + * is not exactly in sync with the server's. + * @default true + */ + trustServerDate?: boolean; + } + + interface CachePolicyObject { + v: number; + t: number; + sh: boolean; + ch: number; + imm: number; + st: number; + resh: Headers; + rescc: { [key: string]: string }; + m: string; + u?: string; + h?: string; + a: boolean; + reqh: Headers | null; + reqcc: { [key: string]: string }; + } + + interface Headers { + [header: string]: string | string[] | undefined; + } + + interface RevalidationPolicy { + /** + * A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace + * the old cached `CachePolicy` with the new one. + */ + policy: CachePolicy; + /** + * Boolean indicating whether the response body has changed. + * + * - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old + * cached response body. + * - If `true`, you should use new response's body (if present), or make another request to the origin + * server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get + * the new resource. + */ + modified: boolean; + matches: boolean; + } +} diff --git a/types/http-cache-semantics/tsconfig.json b/types/http-cache-semantics/tsconfig.json new file mode 100644 index 0000000000..9940b3d2e6 --- /dev/null +++ b/types/http-cache-semantics/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-cache-semantics-tests.ts" + ] +} diff --git a/types/http-cache-semantics/tslint.json b/types/http-cache-semantics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-cache-semantics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 589adf1b66463c8ad7163160417da7e0334259ee Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 28 Jan 2019 00:49:53 +0100 Subject: [PATCH 118/312] [responselike] Add types --- types/responselike/index.d.ts | 34 ++++++++++++++++++++++++ types/responselike/responselike-tests.ts | 10 +++++++ types/responselike/tsconfig.json | 23 ++++++++++++++++ types/responselike/tslint.json | 1 + 4 files changed, 68 insertions(+) create mode 100644 types/responselike/index.d.ts create mode 100644 types/responselike/responselike-tests.ts create mode 100644 types/responselike/tsconfig.json create mode 100644 types/responselike/tslint.json diff --git a/types/responselike/index.d.ts b/types/responselike/index.d.ts new file mode 100644 index 0000000000..7152388232 --- /dev/null +++ b/types/responselike/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for responselike 1.0 +// Project: https://github.com/lukechilds/responselike#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { IncomingMessage } from 'http'; +import { Stream } from 'stream'; + +export = ResponseLike; + +/** + * Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + */ +declare class ResponseLike extends Stream.Readable { + statusCode: number; + headers: { [header: string]: string | string[] | undefined }; + body: Buffer; + url: string; + + /** + * @param statusCode HTTP response status code. + * @param headers HTTP headers object. Keys will be automatically lowercased. + * @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + * @param url Request URL string. + */ + constructor( + statusCode: number, + headers: { [header: string]: string | string[] | undefined }, + body: Buffer, + url: string + ); +} diff --git a/types/responselike/responselike-tests.ts b/types/responselike/responselike-tests.ts new file mode 100644 index 0000000000..95c5e4f701 --- /dev/null +++ b/types/responselike/responselike-tests.ts @@ -0,0 +1,10 @@ +import Response = require('responselike'); + +const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); + +response.statusCode; // $ExpectType number +response.headers; // $ExpectType { [header: string]: string | string[] | undefined; } +response.body; // $ExpectType Buffer +response.url; // $ExpectType string + +response.pipe(process.stdout); diff --git a/types/responselike/tsconfig.json b/types/responselike/tsconfig.json new file mode 100644 index 0000000000..2c0a9e392b --- /dev/null +++ b/types/responselike/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", + "responselike-tests.ts" + ] +} diff --git a/types/responselike/tslint.json b/types/responselike/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/responselike/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 909f8b2069ab20fbf15d87561867bd6be789582e Mon Sep 17 00:00:00 2001 From: denis Date: Mon, 28 Jan 2019 01:02:33 +0100 Subject: [PATCH 119/312] Fix jQuery compatibility Linting `unified-signatures` for dropdown --- types/bootstrap/v3/bootstrap-tests.ts | 33 +++++++++++- types/bootstrap/v3/index.d.ts | 73 +++++++++++++++------------ 2 files changed, 71 insertions(+), 35 deletions(-) diff --git a/types/bootstrap/v3/bootstrap-tests.ts b/types/bootstrap/v3/bootstrap-tests.ts index 7711b5792d..e834903867 100644 --- a/types/bootstrap/v3/bootstrap-tests.ts +++ b/types/bootstrap/v3/bootstrap-tests.ts @@ -1,11 +1,21 @@ declare let aHtmlElement: HTMLElement; +// -------------------------------------------------------------------------------------- +// jQuery backward compatibility +// -------------------------------------------------------------------------------------- + +$(".dropdown").on("affixed.bs.affix", (e) => { + e.stopPropagation(); +}); + // -------------------------------------------------------------------------------------- // Modal // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".modal").modal(); +// $ExpectType JQuery $(".modal").modal("show"); $(".modal").modal("toggle"); @@ -27,8 +37,10 @@ $(".modal").modal({ // Dropdown // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".dropdown").dropdown(); +// $ExpectType JQuery $(".dropdown").dropdown("toggle"); $(".dropdown").on("show.bs.dropdown", (e) => { @@ -39,8 +51,10 @@ $(".dropdown").on("show.bs.dropdown", (e) => { // Scrollspy // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".navbar").scrollspy(); +// $ExpectType JQuery $(".navbar").scrollspy("refresh"); $(".navbar").scrollspy({ @@ -48,7 +62,7 @@ $(".navbar").scrollspy({ offset: 10, }); -$('.navbar').on("activate.bs.scrollspy", () => { +$(".navbar").on("activate.bs.scrollspy", () => { // do something... }); @@ -56,8 +70,10 @@ $('.navbar').on("activate.bs.scrollspy", () => { // Togglable tabs // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".tab").tab(); +// $ExpectType JQuery $(".tab").tab("show"); $(".tab").on("shown.bs.tab", (e) => { @@ -69,8 +85,10 @@ $(".tab").on("shown.bs.tab", (e) => { // Tooltip // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".tooltip").tooltip(); +// $ExpectType JQuery $(".tooltip").tooltip("show"); $(".tooltip").tooltip({ @@ -129,8 +147,10 @@ $(".tooltip").on("hidden.bs.tooltip", () => { // Popover // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".popover").popover(); +// $ExpectType JQuery $(".popover").popover("show"); $(".popover").popover({ @@ -186,8 +206,10 @@ $(".popover").on("hidden.bs.popover", () => { // Alert // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".alert").alert(); +// $ExpectType JQuery $(".alert").alert("close"); $(".alert").on("closed.bs.alert", () => { @@ -198,6 +220,7 @@ $(".alert").on("closed.bs.alert", () => { // Button // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".btn").button("toggle"); $(".btn").button("reset"); @@ -208,8 +231,10 @@ $(".btn").button("Swaps text to any data defined text state."); // Collapse // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".collapse").collapse(); +// $ExpectType JQuery $(".collapse").collapse("toggle"); $(".collapse").collapse({ @@ -225,8 +250,10 @@ $(".collapse").on("hidden.bs.collapse", () => { // Carousel // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".carousel").carousel(); +// $ExpectType JQuery $(".carousel").carousel("cycle"); $(".carousel").carousel(200); @@ -246,7 +273,7 @@ $(".carousel").carousel({ pause: null, }); -$('#myCarousel').on('slide.bs.carousel', (e) => { +$("#myCarousel").on("slide.bs.carousel", (e) => { const dir: "left" | "right" = e.direction; aHtmlElement = e.relatedTarget; }); @@ -255,8 +282,10 @@ $('#myCarousel').on('slide.bs.carousel', (e) => { // Affix // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".affix").affix(); +// $ExpectType JQuery $(".affix").affix("checkPosition"); $(".affix").affix({ diff --git a/types/bootstrap/v3/index.d.ts b/types/bootstrap/v3/index.d.ts index 45dee67370..d3b80a0529 100644 --- a/types/bootstrap/v3/index.d.ts +++ b/types/bootstrap/v3/index.d.ts @@ -7,6 +7,16 @@ /// +// -------------------------------------------------------------------------- +// For jQuery v1 and v2 backward compatibility +// -------------------------------------------------------------------------- + +/** + * Same as jQuery v3 `JQuery.EventHandlerBase`. + */ +type JQueryEventHandlerBase = + (this: TContext, t: T, ...args: any[]) => void | false; + // -------------------------------------------------------------------------- // Some Types and Interfaces // -------------------------------------------------------------------------- @@ -265,7 +275,7 @@ interface AffixOptions { // Events // -------------------------------------------------------------------------------------- -interface CarouselEventHandler extends JQuery.TriggeredEvent { +interface CarouselEventHandler extends JQueryEventObject { /** * The direction in which the carousel is sliding. */ @@ -277,14 +287,14 @@ interface CarouselEventHandler extends JQuery.TriggeredEvent extends JQuery.TriggeredEvent { +interface DropdownsEventHandler extends JQueryEventObject { /** * The toggling anchor element. */ relatedTarget: HTMLElement; } -interface TapEventHandler extends JQuery.TriggeredEvent { +interface TapEventHandler extends JQueryEventObject { /** * * For `show.bs.tab` and `shown.bs.tab`, is the new active tab. * * For `hide.bs.tab`, is the current active tab. @@ -314,7 +324,7 @@ type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.tooltip" | // jQuery // -------------------------------------------------------------------------------------- -interface JQuery { +interface JQuery { /** * Call a method on the modal element: * * `toggle` – Manually toggles a modal. @@ -325,22 +335,19 @@ interface JQuery { * * Returns to the caller before the modal has actually been shown or hidden (i.e. before the `shown.bs.modal` or `hidden.bs.modal` event occurs). */ - modal(action: "toggle" | "show" | "hide" | "handleUpdate"): JQuery; + modal(action: "toggle" | "show" | "hide" | "handleUpdate"): this; /** * Activates a content as a modal. */ - modal(options?: ModalOptions): JQuery; + modal(options?: ModalOptions): this; /** - * Toggles the dropdown menu of a given navbar or tabbed navigation. - */ - dropdown(action: "toggle"): JQuery; - /** - * Toggle contextual overlays for displaying lists of links. - * + * If no _method_ is specified, toggle contextual overlays for displaying lists of links. * The data-api, `data-toggle="dropdown"` is always required to be present on the dropdown's trigger element. + * + * When _method_ `toggle` is specified, toggles the dropdown menu of a given navbar or tabbed navigation. */ - dropdown(): this; + dropdown(action?: "toggle"): this; // tslint:disable:jsdoc-format /** @@ -353,11 +360,11 @@ $('[data-spy="scroll"]').each(function () { ``` */ // tslint:enable:jsdoc-format - scrollspy(action: "refresh"): JQuery; + scrollspy(action: "refresh"): this; /** * Add scrollspy behavior to a topbar navigation. */ - scrollspy(options?: ScrollSpyOptions): JQuery; + scrollspy(options?: ScrollSpyOptions): this; /** * If no _method_ is specified, activates a tab element and content container. Tab should have either a `data-target` or an `href` targeting a container node in the DOM. @@ -367,7 +374,7 @@ $('[data-spy="scroll"]').each(function () { * * Returns to the caller before the tab pane has actually been shown (i.e. before the `shown.bs.tab` event occurs). */ - tab(action?: "show"): JQuery; + tab(action?: "show"): this; /** * Call a method on the tooltip element: @@ -380,11 +387,11 @@ $('[data-spy="scroll"]').each(function () { * Returns to the caller before the tooltip has actually been shown or hidden (i.e. before the `shown.bs.tooltip` or `hidden.bs.tooltip` event occurs). * This is considered a "manual" triggering of the tooltip. */ - tooltip(action: "show" | "hide" | "toggle" | "destroy"): JQuery; + tooltip(action: "show" | "hide" | "toggle" | "destroy"): this; /** * Attaches a tooltip handler to an element collection. */ - tooltip(options?: TooltipOptions): JQuery; + tooltip(options?: TooltipOptions): this; /** * Call a method on the popover element: @@ -397,11 +404,11 @@ $('[data-spy="scroll"]').each(function () { * Returns to the caller before the popover has actually been shown or hidden (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). * This is considered a "manual" triggering of the popover. */ - popover(action: "show" | "hide" | "toggle" | "destroy"): JQuery; + popover(action: "show" | "hide" | "toggle" | "destroy"): this; /** * Initializes popovers for an element collection. */ - popover(options?: PopoverOptions): JQuery; + popover(options?: PopoverOptions): this; /** * If no _method_ is specified, makes an alert listen for click events on descendant elements which have the `data-dismiss="alert"` attribute. @@ -410,7 +417,7 @@ $('[data-spy="scroll"]').each(function () { * When _method_ `close` is specified, closes an alert by removing it from the DOM. If the `.fade` and `.in` classes are present on the element, * the alert will fade out before it is removed. */ - alert(action?: "close"): JQuery; + alert(action?: "close"): this; /** * Call a method on the button element: @@ -418,7 +425,7 @@ $('[data-spy="scroll"]').each(function () { * * `reset` – Resets button state: swaps text to original text. This method is asynchronous and returns before the resetting has actually completed. * * _string_ – Swaps text to any data defined text state. */ - button(action: "toggle" | "reset" | string): JQuery; + button(action: "toggle" | "reset" | string): this; /** * Call a method on the collapsible element: @@ -428,11 +435,11 @@ $('[data-spy="scroll"]').each(function () { * * Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the `shown.bs.collapse` or `hidden.bs.collapse` event occurs). */ - collapse(action: "toggle" | "show" | "hide"): JQuery; + collapse(action: "toggle" | "show" | "hide"): this; /** * Activates a content as a collapsible element. */ - collapse(options?: CollapseOptions): JQuery; + collapse(options?: CollapseOptions): this; /** * Call a method on the carousel element: @@ -444,33 +451,33 @@ $('[data-spy="scroll"]').each(function () { * * Returns to the caller before the target item has been shown (i.e. before the `slid.bs.carousel` event occurs). */ - carousel(action: "cycle" | "pause" | number | "prev" | "next"): JQuery; + carousel(action: "cycle" | "pause" | number | "prev" | "next"): this; /** * Initializes the carousel and starts cycling through items. */ - carousel(options?: CarouselOptions): JQuery; + carousel(options?: CarouselOptions): this; /** * Recalculates the state of the affix based on the dimensions, position, and scroll position of the relevant elements. * The `.affix`, `.affix-top`, and `.affix-bottom` classes are added to or removed from the affixed content according to the new state. * This method needs to be called whenever the dimensions of the affixed content or the target element are changed, to ensure correct positioning of the affixed content. */ - affix(action: "checkPosition"): JQuery; + affix(action: "checkPosition"): this; /** * Activates your content as affixed content. */ - affix(options?: AffixOptions): JQuery; + affix(options?: AffixOptions): this; - on(events: CarouselEvent, handler: JQuery.EventHandlerBase>): this; - on(events: DropdownEvent, handler: JQuery.EventHandlerBase>): this; - on(events: TapEvent, handler: JQuery.EventHandlerBase>): this; + on(events: CarouselEvent, handler: JQueryEventHandlerBase): this; + on(events: DropdownEvent, handler: JQueryEventHandlerBase): this; + on(events: TapEvent, handler: JQueryEventHandlerBase): this; on( events: AffixEvent | AlertEvent | CollapseEvent | PopoverEvent | ScrollspyEvent | TooltipEvent, - handler: JQuery.EventHandler + handler: JQueryEventHandlerBase ): this; /** @deprecated */ - emulateTransitionEnd(duration: number): JQuery; + emulateTransitionEnd(duration: number): this; } // -------------------------------------------------------------------------------------- From 8b1cfe7a876b328c028ea375662a5d0e6c327d5f Mon Sep 17 00:00:00 2001 From: Wu Haotian Date: Mon, 28 Jan 2019 14:10:42 +0800 Subject: [PATCH 120/312] Add definitions for user-event --- types/user-event/index.d.ts | 20 ++++++++++++++++++++ types/user-event/tsconfig.json | 16 ++++++++++++++++ types/user-event/tslint.json | 1 + types/user-event/user-event-tests.ts | 11 +++++++++++ 4 files changed, 48 insertions(+) create mode 100644 types/user-event/index.d.ts create mode 100644 types/user-event/tsconfig.json create mode 100644 types/user-event/tslint.json create mode 100644 types/user-event/user-event-tests.ts diff --git a/types/user-event/index.d.ts b/types/user-event/index.d.ts new file mode 100644 index 0000000000..4c4bebb1f8 --- /dev/null +++ b/types/user-event/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for user-event 1.4 +// Project: https://github.com/Gpx/user-event#readme +// Definitions by: Wu Haotian +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface UserOpts { + allAtOnce?: boolean; + delay?: number; +} +declare const userEvent: { + click: (element: Element | Window) => void; + dblClick: (element: Element | Window) => void; + type: ( + element: Element | Window, + text: string, + userOpts?: UserOpts + ) => Promise; +}; + +export default userEvent; diff --git a/types/user-event/tsconfig.json b/types/user-event/tsconfig.json new file mode 100644 index 0000000000..38348b184c --- /dev/null +++ b/types/user-event/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["dom", "es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "user-event-tests.ts"] +} diff --git a/types/user-event/tslint.json b/types/user-event/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/user-event/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/user-event/user-event-tests.ts b/types/user-event/user-event-tests.ts new file mode 100644 index 0000000000..0ecf6eb439 --- /dev/null +++ b/types/user-event/user-event-tests.ts @@ -0,0 +1,11 @@ +import userEvent, { UserOpts } from "user-event"; + +userEvent.click(document.body); // $ExpectType void +userEvent.dblClick(window); // $ExpectType void +userEvent.type(document.body, "s"); // $ExpectType Promise +userEvent.type(document.body, "s", {}); // $ExpectType Promise +userEvent.type(document.body, "s", { delay: 5000 }); // $ExpectType Promise +userEvent.type(document.body, "s", { allAtOnce: true }); // $ExpectType Promise +userEvent.type(document.body, "s", { delay: 1000, allAtOnce: false }); // $ExpectType Promise + +const u: UserOpts = { delay: 20 }; From 1eabe68093f538e2d6b4b7501430ef012f884207 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Mon, 28 Jan 2019 08:39:02 +0100 Subject: [PATCH 121/312] Fix tests --- types/coinbase/coinbase-tests.ts | 2 +- types/coinbase/index.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts index fb804ac566..e7d53012d7 100644 --- a/types/coinbase/coinbase-tests.ts +++ b/types/coinbase/coinbase-tests.ts @@ -25,7 +25,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined); - account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined); + account.getBuys(null, (error: Error, buy: coinbase.Buy[]): void => undefined); account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 5f9f8682f0..4580179195 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -918,9 +918,9 @@ export class Buy implements Resource { unit_price: UnitPrice; hold_business_days: number; - + is_first_buy: boolean; - + requires_completion_step: boolean; /** From 1d3927ce95423736a880f8390a7bb5e4be17524f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Oddsson?= Date: Mon, 28 Jan 2019 10:24:35 +0000 Subject: [PATCH 122/312] add `ReaderFragment` type to `relay-runtime` --- types/relay-runtime/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 27ae20706c..6589acfd6d 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -23,6 +23,7 @@ export type RelayMutationRequest = any; export type RelayQueryRequest = any; export type ConcreteFragmentDefinition = object; export type ConcreteOperationDefinition = object; +export type ReaderFragment = object; /** * FIXME: RelayContainer used to be typed with ReactClass, but From 04d8b844c5e8080b15ede015df826ab6f89d5aea Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 28 Jan 2019 17:46:34 +0500 Subject: [PATCH 123/312] Add types for react-dev-utils --- types/react-dev-utils/FileSizeReporter.d.ts | 27 ++++++++++ .../InlineChunkHtmlPlugin.d.ts | 11 ++++ .../InterpolateHtmlPlugin.d.ts | 11 ++++ types/react-dev-utils/ModuleScopePlugin.d.ts | 11 ++++ .../WatchMissingNodeModulesPlugin.d.ts | 10 ++++ .../WebpackDevServerUtils.d.ts | 46 ++++++++++++++++ types/react-dev-utils/checkRequiredFiles.d.ts | 9 ++++ types/react-dev-utils/clearConsole.d.ts | 5 ++ types/react-dev-utils/eslintFormatter.d.ts | 9 ++++ .../formatWebpackMessages.d.ts | 16 ++++++ .../getCSSModuleLocalIdent.d.ts | 18 +++++++ types/react-dev-utils/getCacheIdentifier.d.ts | 6 +++ types/react-dev-utils/getProcessForPort.d.ts | 6 +++ types/react-dev-utils/index.d.ts | 7 +++ types/react-dev-utils/launchEditor.d.ts | 8 +++ .../noopServiceWorkerMiddleware.d.ts | 9 ++++ types/react-dev-utils/openBrowser.d.ts | 9 ++++ types/react-dev-utils/printBuildError.d.ts | 6 +++ .../printHostingInstructions.d.ts | 12 +++++ types/react-dev-utils/test/eslintFormatter.ts | 13 +++++ .../test/noopServiceWorkerMiddleware.ts | 6 +++ types/react-dev-utils/test/utils.ts | 31 +++++++++++ types/react-dev-utils/test/webpack-plugins.ts | 22 ++++++++ types/react-dev-utils/test/webpack-utils.ts | 52 +++++++++++++++++++ types/react-dev-utils/tsconfig.json | 45 ++++++++++++++++ types/react-dev-utils/tslint.json | 1 + 26 files changed, 406 insertions(+) create mode 100644 types/react-dev-utils/FileSizeReporter.d.ts create mode 100644 types/react-dev-utils/InlineChunkHtmlPlugin.d.ts create mode 100644 types/react-dev-utils/InterpolateHtmlPlugin.d.ts create mode 100644 types/react-dev-utils/ModuleScopePlugin.d.ts create mode 100644 types/react-dev-utils/WatchMissingNodeModulesPlugin.d.ts create mode 100644 types/react-dev-utils/WebpackDevServerUtils.d.ts create mode 100644 types/react-dev-utils/checkRequiredFiles.d.ts create mode 100644 types/react-dev-utils/clearConsole.d.ts create mode 100644 types/react-dev-utils/eslintFormatter.d.ts create mode 100644 types/react-dev-utils/formatWebpackMessages.d.ts create mode 100644 types/react-dev-utils/getCSSModuleLocalIdent.d.ts create mode 100644 types/react-dev-utils/getCacheIdentifier.d.ts create mode 100644 types/react-dev-utils/getProcessForPort.d.ts create mode 100644 types/react-dev-utils/index.d.ts create mode 100644 types/react-dev-utils/launchEditor.d.ts create mode 100644 types/react-dev-utils/noopServiceWorkerMiddleware.d.ts create mode 100644 types/react-dev-utils/openBrowser.d.ts create mode 100644 types/react-dev-utils/printBuildError.d.ts create mode 100644 types/react-dev-utils/printHostingInstructions.d.ts create mode 100644 types/react-dev-utils/test/eslintFormatter.ts create mode 100644 types/react-dev-utils/test/noopServiceWorkerMiddleware.ts create mode 100644 types/react-dev-utils/test/utils.ts create mode 100644 types/react-dev-utils/test/webpack-plugins.ts create mode 100644 types/react-dev-utils/test/webpack-utils.ts create mode 100644 types/react-dev-utils/tsconfig.json create mode 100644 types/react-dev-utils/tslint.json diff --git a/types/react-dev-utils/FileSizeReporter.d.ts b/types/react-dev-utils/FileSizeReporter.d.ts new file mode 100644 index 0000000000..8b95d43db5 --- /dev/null +++ b/types/react-dev-utils/FileSizeReporter.d.ts @@ -0,0 +1,27 @@ +import webpack = require('webpack'); + +export interface OpaqueFileSizes { + root: string; + sizes: Record; +} + +/** + * Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the + * result value to compare it after the build. + */ +export function measureFileSizesBeforeBuild(buildFolder: string): Promise; + +/** + * Prints the JS and CSS asset sizes after the build, and includes a size + * comparison with `previousFileSizes` that were captured earlier using + * `measureFileSizesBeforeBuild()`. `maxBundleGzipSize` and + * `maxChunkGzipSizemay` may optionally be specified to display a warning when + * the main bundle or a chunk exceeds the specified size (in bytes). + */ +export function printFileSizesAfterBuild( + webpackStats: webpack.Stats, + previousFileSizes: OpaqueFileSizes, + buildFolder: string, + maxBundleGzipSize?: number, + maxChunkGzipSize?: number, +): void; diff --git a/types/react-dev-utils/InlineChunkHtmlPlugin.d.ts b/types/react-dev-utils/InlineChunkHtmlPlugin.d.ts new file mode 100644 index 0000000000..41f35faef6 --- /dev/null +++ b/types/react-dev-utils/InlineChunkHtmlPlugin.d.ts @@ -0,0 +1,11 @@ +import webpack = require('webpack'); +import HtmlWebpackPlugin = require('html-webpack-plugin'); + +/** + * This Webpack plugin inlines script chunks into `index.html`. + */ +declare class InlineChunkHtmlPlugin extends webpack.Plugin { + constructor(htmlWebpackPlugin: HtmlWebpackPlugin, tests: ReadonlyArray); +} + +export = InlineChunkHtmlPlugin; diff --git a/types/react-dev-utils/InterpolateHtmlPlugin.d.ts b/types/react-dev-utils/InterpolateHtmlPlugin.d.ts new file mode 100644 index 0000000000..61357879c4 --- /dev/null +++ b/types/react-dev-utils/InterpolateHtmlPlugin.d.ts @@ -0,0 +1,11 @@ +import webpack = require('webpack'); +import HtmlWebpackPlugin = require('html-webpack-plugin'); + +/** + * This Webpack plugin lets us interpolate custom variables into `index.html`. + */ +declare class InterpolateHtmlPlugin extends webpack.Plugin { + constructor(htmlWebpackPlugin: HtmlWebpackPlugin, replacements: { [key: string]: string }); +} + +export = InterpolateHtmlPlugin; diff --git a/types/react-dev-utils/ModuleScopePlugin.d.ts b/types/react-dev-utils/ModuleScopePlugin.d.ts new file mode 100644 index 0000000000..61d234d712 --- /dev/null +++ b/types/react-dev-utils/ModuleScopePlugin.d.ts @@ -0,0 +1,11 @@ +import webpack = require('webpack'); + +/** + * This Webpack plugin ensures that relative imports from app's source + * directories don't reach outside of it. + */ +declare class ModuleScopePlugin extends webpack.Plugin { + constructor(appSrc: string | ReadonlyArray, allowedFiles?: ReadonlyArray); +} + +export = ModuleScopePlugin; diff --git a/types/react-dev-utils/WatchMissingNodeModulesPlugin.d.ts b/types/react-dev-utils/WatchMissingNodeModulesPlugin.d.ts new file mode 100644 index 0000000000..1ab7cc30be --- /dev/null +++ b/types/react-dev-utils/WatchMissingNodeModulesPlugin.d.ts @@ -0,0 +1,10 @@ +import webpack = require('webpack'); + +/** + * This Webpack plugin ensures `npm install ` forces a project rebuild. + */ +declare class WatchMissingNodeModulesPlugin extends webpack.Plugin { + constructor(nodeModulesPath: string); +} + +export = WatchMissingNodeModulesPlugin; diff --git a/types/react-dev-utils/WebpackDevServerUtils.d.ts b/types/react-dev-utils/WebpackDevServerUtils.d.ts new file mode 100644 index 0000000000..08d2ae0ebe --- /dev/null +++ b/types/react-dev-utils/WebpackDevServerUtils.d.ts @@ -0,0 +1,46 @@ +import webpack = require('webpack'); +import WebpackDevServer = require('webpack-dev-server'); + +export interface Urls { + lanUrlForConfig?: string; + lanUrlForTerminal?: string; + localUrlForTerminal: string; + localUrlForBrowser: string; +} + +/** + * Returns a Promise resolving to either `defaultPort` or next available port + * if the user confirms it is okay to do. If the port is taken and the user has + * refused to use another port, or if the terminal is not interactive and can’t + * present user with the choice, resolves to `null`. + */ +export function choosePort(host: string, defaultPort: number): Promise; + +/** + * Creates a Webpack compiler instance for WebpackDevServer with built-in + * helpful messages. Takes the `require('webpack')` entry point as the first + * argument. To provide the `urls` argument, use `prepareUrls()` described + * below. + */ +export function createCompiler( + _webpack: typeof webpack, + config: webpack.Configuration, + appName: string, + urls: Urls, + useYarn: boolean, +): webpack.Compiler; + +/** + * Creates a WebpackDevServer `proxy` configuration object from the `proxy` + * setting in `package.json`. + */ +export function prepareProxy( + proxySetting: any, + appPublicFolder: string, +): WebpackDevServer.Configuration; + +/** + * Returns an object with local and remote URLs for the development server. + * Pass this object to `createCompiler()` described above. + */ +export function prepareUrls(protocol: string, host: string, port: number): Urls; diff --git a/types/react-dev-utils/checkRequiredFiles.d.ts b/types/react-dev-utils/checkRequiredFiles.d.ts new file mode 100644 index 0000000000..40a8e45c88 --- /dev/null +++ b/types/react-dev-utils/checkRequiredFiles.d.ts @@ -0,0 +1,9 @@ +/** + * Makes sure that all passed files exist. + * + * Filenames are expected to be absolute. + * + * If a file is not found, prints a warning message and returns `false`. + */ +declare function checkRequiredFiles(files: ReadonlyArray): boolean; +export = checkRequiredFiles; diff --git a/types/react-dev-utils/clearConsole.d.ts b/types/react-dev-utils/clearConsole.d.ts new file mode 100644 index 0000000000..d3ae28c991 --- /dev/null +++ b/types/react-dev-utils/clearConsole.d.ts @@ -0,0 +1,5 @@ +/** + * Clears the console, hopefully in a cross-platform way. + */ +declare function clearConsole(): void; +export = clearConsole; diff --git a/types/react-dev-utils/eslintFormatter.d.ts b/types/react-dev-utils/eslintFormatter.d.ts new file mode 100644 index 0000000000..b5a10718d2 --- /dev/null +++ b/types/react-dev-utils/eslintFormatter.d.ts @@ -0,0 +1,9 @@ +import { CLIEngine } from 'eslint'; + +/** + * This is our custom ESLint formatter that integrates well with + * Create React App console output. + */ +declare function eslintFormatter(results: ReadonlyArray): string; + +export = eslintFormatter; diff --git a/types/react-dev-utils/formatWebpackMessages.d.ts b/types/react-dev-utils/formatWebpackMessages.d.ts new file mode 100644 index 0000000000..8e1994feea --- /dev/null +++ b/types/react-dev-utils/formatWebpackMessages.d.ts @@ -0,0 +1,16 @@ +declare namespace formatWebpackMessages { + interface WebpackMessages { + errors: string[]; + warnings: string[]; + } +} + +/** + * Extracts and prettifies warning and error messages from webpack + * [stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object. + */ +declare function formatWebpackMessages( + json: formatWebpackMessages.WebpackMessages, +): formatWebpackMessages.WebpackMessages; + +export = formatWebpackMessages; diff --git a/types/react-dev-utils/getCSSModuleLocalIdent.d.ts b/types/react-dev-utils/getCSSModuleLocalIdent.d.ts new file mode 100644 index 0000000000..a443355f8b --- /dev/null +++ b/types/react-dev-utils/getCSSModuleLocalIdent.d.ts @@ -0,0 +1,18 @@ +import webpack = require('webpack'); + +/** + * Creates a class name for CSS Modules that uses either the filename or folder + * name if named `index.module.css`. + * + * For `MyFolder/MyComponent.module.css` and class `MyClass` the output will be + * `MyComponent.module_MyClass__[hash]`. For `MyFolder/index.module.css` and + * class `MyClass` the output will be `MyFolder_MyClass__[hash]` + */ +declare function getCSSModuleLocalIdent( + context: webpack.loader.LoaderContext, + localIdentName: string, + localName: string, + options: object, +): string; + +export = getCSSModuleLocalIdent; diff --git a/types/react-dev-utils/getCacheIdentifier.d.ts b/types/react-dev-utils/getCacheIdentifier.d.ts new file mode 100644 index 0000000000..86cbb093e3 --- /dev/null +++ b/types/react-dev-utils/getCacheIdentifier.d.ts @@ -0,0 +1,6 @@ +/** + * Returns a cache identifier (string) consisting of the specified environment + * and related package versions. + */ +declare function getCacheIdentifier(environment: string, packages: ReadonlyArray): string; +export = getCacheIdentifier; diff --git a/types/react-dev-utils/getProcessForPort.d.ts b/types/react-dev-utils/getProcessForPort.d.ts new file mode 100644 index 0000000000..5c2c9aac62 --- /dev/null +++ b/types/react-dev-utils/getProcessForPort.d.ts @@ -0,0 +1,6 @@ +/** + * Finds the currently running process on `port`. + * Returns a string containing the name and directory. + */ +declare function getProcessForPort(port: number): string | null; +export = getProcessForPort; diff --git a/types/react-dev-utils/index.d.ts b/types/react-dev-utils/index.d.ts new file mode 100644 index 0000000000..49bf463b73 --- /dev/null +++ b/types/react-dev-utils/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for react-dev-utils 7.0 +// Project: https://github.com/facebook/create-react-app#readme +// Definitions by: ark120202 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export {}; diff --git a/types/react-dev-utils/launchEditor.d.ts b/types/react-dev-utils/launchEditor.d.ts new file mode 100644 index 0000000000..5132d488ba --- /dev/null +++ b/types/react-dev-utils/launchEditor.d.ts @@ -0,0 +1,8 @@ +/** + * On macOS, tries to find a known running editor process and opens the file in + * it. It can also be explicitly configured by `REACT_EDITOR`, `VISUAL`, or + * `EDITOR` environment variables. For example, you can put `REACT_EDITOR=atom` + * in your `.env.local` file, and Create React App will respect that. + */ +declare function launchEditor(fileName: string, lineNumber: number, colNumber?: number): void; +export = launchEditor; diff --git a/types/react-dev-utils/noopServiceWorkerMiddleware.d.ts b/types/react-dev-utils/noopServiceWorkerMiddleware.d.ts new file mode 100644 index 0000000000..8f52455324 --- /dev/null +++ b/types/react-dev-utils/noopServiceWorkerMiddleware.d.ts @@ -0,0 +1,9 @@ +import express = require('express'); + +/** + * Returns Express middleware that serves a `/service-worker.js` that resets + * any previously set service worker configuration. Useful for development. + */ +declare function noopServiceWorkerMiddleware(): express.Handler; + +export = noopServiceWorkerMiddleware; diff --git a/types/react-dev-utils/openBrowser.d.ts b/types/react-dev-utils/openBrowser.d.ts new file mode 100644 index 0000000000..1c87eee617 --- /dev/null +++ b/types/react-dev-utils/openBrowser.d.ts @@ -0,0 +1,9 @@ +/** + * Attempts to open the browser with a given URL. + * + * On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript. + * + * Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior. + */ +declare function openBrowser(url: string): boolean; +export = openBrowser; diff --git a/types/react-dev-utils/printBuildError.d.ts b/types/react-dev-utils/printBuildError.d.ts new file mode 100644 index 0000000000..c145e32d8c --- /dev/null +++ b/types/react-dev-utils/printBuildError.d.ts @@ -0,0 +1,6 @@ +/** + * Prettify some known build errors. + * Pass an Error object to log a prettified error message in the console. + */ +declare function printBuildError(error: Error): void; +export = printBuildError; diff --git a/types/react-dev-utils/printHostingInstructions.d.ts b/types/react-dev-utils/printHostingInstructions.d.ts new file mode 100644 index 0000000000..946b3118cb --- /dev/null +++ b/types/react-dev-utils/printHostingInstructions.d.ts @@ -0,0 +1,12 @@ +/** + * Prints hosting instructions after the project is built. + */ +declare function printHostingInstructions( + appPackage: object, + publicUrl: string, + publicPath: string, + buildFolder: string, + useYarn: boolean, +): void; + +export = printHostingInstructions; diff --git a/types/react-dev-utils/test/eslintFormatter.ts b/types/react-dev-utils/test/eslintFormatter.ts new file mode 100644 index 0000000000..d6fae121cc --- /dev/null +++ b/types/react-dev-utils/test/eslintFormatter.ts @@ -0,0 +1,13 @@ +import { CLIEngine } from 'eslint'; +import eslintFormatter = require('react-dev-utils/eslintFormatter'); + +const { results } = new CLIEngine({}).executeOnText(''); + +// $ExpectError +eslintFormatter(['error']); + +// $ExpectError +eslintFormatter([results]); + +// $ExpectType string +eslintFormatter(results); diff --git a/types/react-dev-utils/test/noopServiceWorkerMiddleware.ts b/types/react-dev-utils/test/noopServiceWorkerMiddleware.ts new file mode 100644 index 0000000000..37f5b85f04 --- /dev/null +++ b/types/react-dev-utils/test/noopServiceWorkerMiddleware.ts @@ -0,0 +1,6 @@ +import express = require('express'); +import noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware'); + +const app = express(); +app.use(noopServiceWorkerMiddleware()); +app.listen(8080); diff --git a/types/react-dev-utils/test/utils.ts b/types/react-dev-utils/test/utils.ts new file mode 100644 index 0000000000..6bb535ba2a --- /dev/null +++ b/types/react-dev-utils/test/utils.ts @@ -0,0 +1,31 @@ +import webpack = require('webpack'); +import checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +import clearConsole = require('react-dev-utils/clearConsole'); +import getProcessForPort = require('react-dev-utils/getProcessForPort'); +import launchEditor = require('react-dev-utils/launchEditor'); +import openBrowser = require('react-dev-utils/openBrowser'); +import printHostingInstructions = require('react-dev-utils/printHostingInstructions'); +import getCacheIdentifier = require('react-dev-utils/getCacheIdentifier'); + +// $ExpectType boolean +checkRequiredFiles(['public/index.html', 'src/index.js']); + +// $ExpectType void +clearConsole(); + +// $ExpectType string | null +getProcessForPort(3000); + +// $ExpectType void +launchEditor(__filename, 2); +// $ExpectType void +launchEditor(__filename, 2, 10); + +// $ExpectType boolean +openBrowser('http://localhost:3000'); + +// $ExpectType void +printHostingInstructions({}, '', '', 'build', true); + +// $ExpectType string +getCacheIdentifier('prod', ['react-dev-utils', 'chalk']); diff --git a/types/react-dev-utils/test/webpack-plugins.ts b/types/react-dev-utils/test/webpack-plugins.ts new file mode 100644 index 0000000000..a72c6b823f --- /dev/null +++ b/types/react-dev-utils/test/webpack-plugins.ts @@ -0,0 +1,22 @@ +import webpack = require('webpack'); +import HtmlWebpackPlugin = require('html-webpack-plugin'); +import InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); +import InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin'); +import ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); +import WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); + +// $ExpectError +new InterpolateHtmlPlugin(HtmlWebpackPlugin, { PUBLIC_URL: 0 }); +const plugin1 = new InterpolateHtmlPlugin(HtmlWebpackPlugin, { PUBLIC_URL: '' }); + +// $ExpectError +new InlineChunkHtmlPlugin({}, [/runtime/]); +const plugin2 = new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime/]); + +const plugin3 = new ModuleScopePlugin('src', ['package.json']); + +const plugin4 = new WatchMissingNodeModulesPlugin('node_modules'); + +const configWithPlugins: webpack.Configuration = { + plugins: [plugin1, plugin2, plugin3, plugin4] +}; diff --git a/types/react-dev-utils/test/webpack-utils.ts b/types/react-dev-utils/test/webpack-utils.ts new file mode 100644 index 0000000000..d68483c0a2 --- /dev/null +++ b/types/react-dev-utils/test/webpack-utils.ts @@ -0,0 +1,52 @@ +import webpack = require('webpack'); +import FileSizeReporter = require('react-dev-utils/FileSizeReporter'); +import formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); +import printBuildError = require('react-dev-utils/printBuildError'); +import WebpackDevServerUtils = require('react-dev-utils/WebpackDevServerUtils'); +import getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); + +FileSizeReporter.measureFileSizesBeforeBuild('src').then(previousFileSizes => { + webpack().run((err, webpackStats) => { + FileSizeReporter.printFileSizesAfterBuild(webpackStats, previousFileSizes, 'src'); + }); +}); + +webpack().run((err, stats) => { + const rawMessages = stats.toJson(); + const messages = formatWebpackMessages(rawMessages); + if (!messages.errors.length && !messages.warnings.length) { + console.log('Compiled successfully!'); + } + if (messages.errors.length) { + console.log('Failed to compile.'); + messages.errors.forEach(e => console.log(e)); + return; + } + if (messages.warnings.length) { + console.log('Compiled with warnings.'); + messages.warnings.forEach(w => console.log(w)); + } +}); + +webpack().run((err) => { + if (err) printBuildError(err); +}); + +// $ExpectType Promise +WebpackDevServerUtils.choosePort('localhost', 3000); + +// $ExpectType Urls +const urls = WebpackDevServerUtils.prepareUrls('http', 'localhost', 3000); + +// $ExpectType Compiler +WebpackDevServerUtils.createCompiler(webpack, {}, 'app', urls, true); + +// $ExpectType Configuration +WebpackDevServerUtils.prepareProxy(undefined, 'build'); + +const loaderContext: webpack.loader.LoaderContext = null!; +// $ExpectType string +getCSSModuleLocalIdent(loaderContext, '', '', {}); + +// $ExpectError +getCSSModuleLocalIdent({}, '', '', {}); diff --git a/types/react-dev-utils/tsconfig.json b/types/react-dev-utils/tsconfig.json new file mode 100644 index 0000000000..dc5c861101 --- /dev/null +++ b/types/react-dev-utils/tsconfig.json @@ -0,0 +1,45 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "checkRequiredFiles.d.ts", + "clearConsole.d.ts", + "eslintFormatter.d.ts", + "FileSizeReporter.d.ts", + "formatWebpackMessages.d.ts", + "getCacheIdentifier.d.ts", + "getCSSModuleLocalIdent.d.ts", + "getProcessForPort.d.ts", + "InlineChunkHtmlPlugin.d.ts", + "InterpolateHtmlPlugin.d.ts", + "launchEditor.d.ts", + "ModuleScopePlugin.d.ts", + "noopServiceWorkerMiddleware.d.ts", + "openBrowser.d.ts", + "printBuildError.d.ts", + "printHostingInstructions.d.ts", + "WatchMissingNodeModulesPlugin.d.ts", + "WebpackDevServerUtils.d.ts", + "test/eslintFormatter.ts", + "test/noopServiceWorkerMiddleware.ts", + "test/utils.ts", + "test/webpack-plugins.ts", + "test/webpack-utils.ts" + ] +} diff --git a/types/react-dev-utils/tslint.json b/types/react-dev-utils/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-dev-utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9c52db4e04dba26365933c5a0833f092b36229a8 Mon Sep 17 00:00:00 2001 From: Kyle Uehlein Date: Mon, 28 Jan 2019 11:35:10 -0500 Subject: [PATCH 124/312] [@types/node] add definition for child_process.execFile options --- types/node/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index c63b6c892b..417782b2f3 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -32,6 +32,7 @@ // Zane Hannan AU // Jeremie Rodriguez // Samuel Ainsworth +// Kyle Uehlein // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -2886,6 +2887,7 @@ declare module "child_process" { gid?: number; windowsHide?: boolean; windowsVerbatimArguments?: boolean; + shell?: boolean | string; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { encoding: BufferEncoding; From d3dc58f92271d04961b9bf8e97a20e87af2ffc7f Mon Sep 17 00:00:00 2001 From: taozhi8833998 Date: Tue, 29 Jan 2019 01:11:52 +0800 Subject: [PATCH 125/312] Added type definitions for node-sql-parser --- types/node-sql-parser/index.d.ts | 97 +++++++++++++++++++ .../node-sql-parser/node-sql-parser-tests.ts | 19 ++++ types/node-sql-parser/tsconfig.json | 25 +++++ types/node-sql-parser/tslint.json | 1 + 4 files changed, 142 insertions(+) create mode 100644 types/node-sql-parser/index.d.ts create mode 100644 types/node-sql-parser/node-sql-parser-tests.ts create mode 100644 types/node-sql-parser/tsconfig.json create mode 100644 types/node-sql-parser/tslint.json diff --git a/types/node-sql-parser/index.d.ts b/types/node-sql-parser/index.d.ts new file mode 100644 index 0000000000..c711212c63 --- /dev/null +++ b/types/node-sql-parser/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for node-sql-parser 1.0 +// Project: https://github.com/taozhi8833998/node-sql-parser#readme +// Definitions by: taozhi8833998 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export interface With { + name: string; + stmt: any[]; + columns?: any[]; +} +export type WhilteListCheckMode = 'table' | 'column'; +export interface TableColumnAst { + tableList: string[]; + columnsList: string[]; + ast: AST[] | AST; +} +export interface From { + db: string | null; + table: string; + as: string | null; +} +export interface Dual { + type: 'dual'; +} +export interface Limit { + type: string; + value: number; +} +export interface OrderBy { + type: 'ASC' | 'DESC'; + expr: any; +} +export interface ColumnRef { + type: 'column_ref'; + table: string | null; + column: string; +} +export interface SetList { + column: string; + value: any; + table: string | null; +} +export interface InsertReplaceValue { + type: 'expr_list'; + value: any[]; +} +export interface Select { + with: With | null; + type: 'select'; + options: any[] | null; + distinct: 'DISTINCT' | null; + columns: any[] | '*'; + from: Array | null; + where: any; + groupby: ColumnRef[] | null; + having: any[] | null; + orderby: OrderBy[] | null; + limit: Limit[] | null; +} +export interface Insert_Replace { + type: 'replace' | 'insert'; + db: string | null; + table: string; + columns: string[] | null; + values: InsertReplaceValue[]; +} +export interface Update { + type: 'udpate'; + db: string | null; + table: string; + set: SetList[]; + where: any; +} +export interface Delete { + type: 'delete'; + tables: any; + from: Array; + where: any; +} +export type AST = Select | Insert_Replace | Update | Delete; + +export class Parser { + constructor(); + + parse(sql: string): TableColumnAst; + + astify(sql: string): AST[] | AST; + + sqlify(ast: AST[] | AST): string; + + whiteListCheck(sql: string, whiteList: string[], type?: WhilteListCheckMode): Error | undefined; + + tableList(sql: string): string[]; + + columnList(sql: string): string[]; +} diff --git a/types/node-sql-parser/node-sql-parser-tests.ts b/types/node-sql-parser/node-sql-parser-tests.ts new file mode 100644 index 0000000000..050c69a855 --- /dev/null +++ b/types/node-sql-parser/node-sql-parser-tests.ts @@ -0,0 +1,19 @@ +import { Parser } from 'node-sql-parser'; + +const parser = new Parser(); +const sql = 'select id from tableA'; + +// $ExpectType Select | Insert_Replace | Update | Delete | AST[] +const selectAst = parser.astify(sql); + +// $ExpectType string +parser.sqlify(selectAst); + +// $ExpectType string[] +parser.tableList(sql); + +// $ExpectType string[] +parser.columnList(sql); + +// $ExpectType Error | undefined +parser.whiteListCheck(sql, ['select::null::tableA'], 'table'); diff --git a/types/node-sql-parser/tsconfig.json b/types/node-sql-parser/tsconfig.json new file mode 100644 index 0000000000..c7f24afb95 --- /dev/null +++ b/types/node-sql-parser/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-sql-parser-tests.ts" + ] +} diff --git a/types/node-sql-parser/tslint.json b/types/node-sql-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-sql-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 06261e9c3998e4080dadb903882e6415bf44e295 Mon Sep 17 00:00:00 2001 From: Thomas Kosiewski Date: Mon, 28 Jan 2019 19:23:11 +0100 Subject: [PATCH 126/312] Added typings for Next-seo --- types/next-seo/index.d.ts | 85 ++++++++++++++++++++++++++++++++ types/next-seo/next-seo-tests.ts | 48 ++++++++++++++++++ types/next-seo/tsconfig.json | 25 ++++++++++ types/next-seo/tslint.json | 1 + 4 files changed, 159 insertions(+) create mode 100644 types/next-seo/index.d.ts create mode 100644 types/next-seo/next-seo-tests.ts create mode 100644 types/next-seo/tsconfig.json create mode 100644 types/next-seo/tslint.json diff --git a/types/next-seo/index.d.ts b/types/next-seo/index.d.ts new file mode 100644 index 0000000000..a3542c9fe9 --- /dev/null +++ b/types/next-seo/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for next-seo 1.10 +// Project: https://github.com/garmeeh/next-seo#readme +// Definitions by: Thomas Kosiewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Component } from "react"; + +declare module "next-seo" { + interface INextSeoProps { + config: IConfig; + } + + interface IConfig { + title?: string; + titleTemplate?: string; + description?: string; + canonical?: string; + + dangerouslySetAllPagesToNoIndex?: boolean; + noindex?: boolean; + + twitter?: ITwitter; + facebook?: IFacebook; + openGraph?: IOpenGraph; + } + + interface ITwitter { + cardType?: string; + site?: string; + handle?: string; + } + + interface IFacebook { + appId?: number; + } + + interface IOpenGraph { + url?: string; + type?: string; + title?: string; + description?: string; + images?: ReadonlyArray; + defaultImageHeight?: number; + defaultImageWidth?: number; + locale?: string; + site_name?: string; + + profile?: IOpenGraphProfile; + book?: IOpenGraphBook; + article?: IOpenGraphArticle; + } + + interface IOpenGraphImages { + url?: string, + width?: number, + height?: number, + alt?: string, + } + + interface IOpenGraphProfile { + firstName?: string; + lastName?: string; + username?: string; + gender?: string; + } + + interface IOpenGraphBook { + authors?: ReadonlyArray; + isbn?: string; + releaseDate?: string; + tags?: ReadonlyArray; + } + + interface IOpenGraphArticle { + publishedTime?: string; + modifiedTime?: string; + expirationTime?: string; + + authors?: ReadonlyArray; + section?: string; + tags?: ReadonlyArray; + } + + export default class NextSeo extends Component { } +} diff --git a/types/next-seo/next-seo-tests.ts b/types/next-seo/next-seo-tests.ts new file mode 100644 index 0000000000..3c2da4b032 --- /dev/null +++ b/types/next-seo/next-seo-tests.ts @@ -0,0 +1,48 @@ +import NextSeo from 'next-seo'; + +new NextSeo({ + config: { + canonical: "", + dangerouslySetAllPagesToNoIndex: false, + description: "", + facebook: { + appId: 0, + }, + noindex: false, + openGraph: { + book: { + authors: [""], + isbn: "", + releaseDate: "", + tags: [""], + }, + defaultImageHeight: 0, + defaultImageWidth: 0, + description: "", + images: [{ + alt: "", + height: 0, + url: "", + width: 0, + }], + locale: "", + profile: { + firstName: "", + gender: "", + lastName: "", + username: "", + }, + site_name: "", + title: "", + type: "", + url: "", + }, + title: "", + titleTemplate: "", + twitter: { + cardType: "", + handle: "", + site: "", + }, + }, +}); diff --git a/types/next-seo/tsconfig.json b/types/next-seo/tsconfig.json new file mode 100644 index 0000000000..faea26b9bc --- /dev/null +++ b/types/next-seo/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "next-seo-tests.ts" + ] +} diff --git a/types/next-seo/tslint.json b/types/next-seo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/next-seo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ac4b9e6cdd80c9bcda463b8024ae501cf5732cdd Mon Sep 17 00:00:00 2001 From: Thomas Kosiewski Date: Mon, 28 Jan 2019 19:44:37 +0100 Subject: [PATCH 127/312] Next-seo: Test fixes --- types/next-seo/index.d.ts | 153 +++++++++++++++++++------------------- 1 file changed, 76 insertions(+), 77 deletions(-) diff --git a/types/next-seo/index.d.ts b/types/next-seo/index.d.ts index a3542c9fe9..8d7c487393 100644 --- a/types/next-seo/index.d.ts +++ b/types/next-seo/index.d.ts @@ -2,84 +2,83 @@ // Project: https://github.com/garmeeh/next-seo#readme // Definitions by: Thomas Kosiewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 import { Component } from "react"; -declare module "next-seo" { - interface INextSeoProps { - config: IConfig; - } - - interface IConfig { - title?: string; - titleTemplate?: string; - description?: string; - canonical?: string; - - dangerouslySetAllPagesToNoIndex?: boolean; - noindex?: boolean; - - twitter?: ITwitter; - facebook?: IFacebook; - openGraph?: IOpenGraph; - } - - interface ITwitter { - cardType?: string; - site?: string; - handle?: string; - } - - interface IFacebook { - appId?: number; - } - - interface IOpenGraph { - url?: string; - type?: string; - title?: string; - description?: string; - images?: ReadonlyArray; - defaultImageHeight?: number; - defaultImageWidth?: number; - locale?: string; - site_name?: string; - - profile?: IOpenGraphProfile; - book?: IOpenGraphBook; - article?: IOpenGraphArticle; - } - - interface IOpenGraphImages { - url?: string, - width?: number, - height?: number, - alt?: string, - } - - interface IOpenGraphProfile { - firstName?: string; - lastName?: string; - username?: string; - gender?: string; - } - - interface IOpenGraphBook { - authors?: ReadonlyArray; - isbn?: string; - releaseDate?: string; - tags?: ReadonlyArray; - } - - interface IOpenGraphArticle { - publishedTime?: string; - modifiedTime?: string; - expirationTime?: string; - - authors?: ReadonlyArray; - section?: string; - tags?: ReadonlyArray; - } - - export default class NextSeo extends Component { } +export interface NextSeoProps { + config: Config; } + +export interface Config { + title?: string; + titleTemplate?: string; + description?: string; + canonical?: string; + + dangerouslySetAllPagesToNoIndex?: boolean; + noindex?: boolean; + + twitter?: Twitter; + facebook?: Facebook; + openGraph?: OpenGraph; +} + +export interface Twitter { + cardType?: string; + site?: string; + handle?: string; +} + +export interface Facebook { + appId?: number; +} + +export interface OpenGraph { + url?: string; + type?: string; + title?: string; + description?: string; + images?: ReadonlyArray; + defaultImageHeight?: number; + defaultImageWidth?: number; + locale?: string; + site_name?: string; + + profile?: OpenGraphProfile; + book?: OpenGraphBook; + article?: OpenGraphArticle; +} + +export interface OpenGraphImages { + url?: string; + width?: number; + height?: number; + alt?: string; +} + +export interface OpenGraphProfile { + firstName?: string; + lastName?: string; + username?: string; + gender?: string; +} + +export interface OpenGraphBook { + authors?: ReadonlyArray; + isbn?: string; + releaseDate?: string; + tags?: ReadonlyArray; +} + +export interface OpenGraphArticle { + publishedTime?: string; + modifiedTime?: string; + expirationTime?: string; + + authors?: ReadonlyArray; + section?: string; + tags?: ReadonlyArray; +} + +export default class NextSeo extends Component { } From 16d81a789790cc86345629712444eb26623d4196 Mon Sep 17 00:00:00 2001 From: Andrew MacLeay Date: Mon, 28 Jan 2019 14:32:27 -0500 Subject: [PATCH 128/312] Allow withInfo to be used as top-level story decorator This allows the syntax [suggested by the README](https://github.com/storybooks/storybook/blob/dc38ae87bb1ef80ccd48b1695009e36632cbe5ee/addons/info/README.md#basic-usage) --- types/storybook__addon-info/index.d.ts | 6 +++++- types/storybook__addon-info/storybook__addon-info-tests.tsx | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/types/storybook__addon-info/index.d.ts b/types/storybook__addon-info/index.d.ts index 111f7dc54d..a6c463f5d9 100644 --- a/types/storybook__addon-info/index.d.ts +++ b/types/storybook__addon-info/index.d.ts @@ -6,7 +6,7 @@ // TypeScript Version: 2.8 import * as React from 'react'; -import { RenderFunction } from '@storybook/react'; +import { RenderFunction, StoryDecorator } from '@storybook/react'; export interface WrapStoryProps { storyFn?: RenderFunction; @@ -29,6 +29,10 @@ export interface Options { maxPropStringLength?: number; } +// TODO: it would be better to use type inference for the parameters +// type DecoratorParams = StoryDecorator extends (...a: infer A) => any ? A: never; +export function withInfo(story: RenderFunction, context: { kind: string, story: string }): ReturnType; +// Legacy, but supported export function withInfo(textOrOptions?: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; export function setDefaults(newDefaults: Options): Options; diff --git a/types/storybook__addon-info/storybook__addon-info-tests.tsx b/types/storybook__addon-info/storybook__addon-info-tests.tsx index 46fd799314..505780bf7e 100644 --- a/types/storybook__addon-info/storybook__addon-info-tests.tsx +++ b/types/storybook__addon-info/storybook__addon-info-tests.tsx @@ -1,11 +1,13 @@ /// import * as React from 'react'; -import { storiesOf } from '@storybook/react'; +import { addDecorator, storiesOf } from '@storybook/react'; import { setDefaults, withInfo } from '@storybook/addon-info'; const { Component } = React; +addDecorator(withInfo); + setDefaults({ inline: false, propTables: false From 157516ea3499d503e7f201729da2e5d7eb61a1c7 Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Mon, 28 Jan 2019 12:32:49 -0700 Subject: [PATCH 129/312] [@types/opossum] Add new CircuitBreaker.shutdown(). https://github.com/nodeshift/opossum/pull/250 --- types/opossum/index.d.ts | 4 +++- types/opossum/opossum-tests.ts | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts index b17a1dd0be..612615ad86 100644 --- a/types/opossum/index.d.ts +++ b/types/opossum/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for opossum 1.9 +// Type definitions for opossum 1.10 // Project: https://github.com/nodeshift/opossum // Definitions by: Quinn Langille // Willy Zhang @@ -23,6 +23,7 @@ export class CircuitBreaker extends EventEmitter { readonly closed: boolean; readonly opened: boolean; readonly halfOpen: boolean; + readonly isShutdown: boolean; readonly status: Status; readonly stats: Stats; readonly hystrixStats: HystrixStats; @@ -40,6 +41,7 @@ export class CircuitBreaker extends EventEmitter { func: (...args: any[]) => Promise, interval?: number ): void; + shutdown(): void; } export enum Event { diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts index ebbf0bea47..69d64497f0 100644 --- a/types/opossum/opossum-tests.ts +++ b/types/opossum/opossum-tests.ts @@ -39,6 +39,7 @@ breaker.closed; // $ExpectType boolean breaker.opened; // $ExpectType boolean breaker.halfOpen; // $ExpectType boolean breaker.warmUp; // $ExpectType boolean +breaker.isShutdown; // $ExpectType boolean breaker.volumeThreshold; // $ExpectType number breaker.status.stats.latencyMean; // $ExpectType number breaker.stats.latencyTimes; // $ExpectType number[] @@ -49,6 +50,7 @@ breaker.open(); // $ExpectType void breaker.close(); // $ExpectType void breaker.disable(); // $ExpectType void breaker.enable(); // $ExpectType void +breaker.shutdown(); // $ExpectType void // The following are examples are from the libs README and official documentation // https://nodeshift.github.io/opossum/index.html. From 78928ae025f2b796abbd4042c0c70ee15b072080 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Mon, 28 Jan 2019 11:49:26 -0800 Subject: [PATCH 130/312] [office-js] Outlook preview updates --- types/office-js/index.d.ts | 283 +++++++++++++++++++++++++++++++++++++ 1 file changed, 283 insertions(+) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index f0fee147ba..ea804993a1 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -7713,6 +7713,31 @@ declare namespace Office { */ Appointment = "appointment" } + /** + * Specifies an appointment's location type. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * @beta + */ + enum LocationType { + /** + * A custom location. + */ + Custom = "custom", + /** + * A conference room or similar resource. + */ + ConferenceRoom = "conferenceRoom" + } /** * Specifies the month. * @@ -9367,6 +9392,173 @@ declare namespace Office { */ emailAddress: string; } + /** + * Represents the set of locations on an appointment. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * @beta + */ + interface EnhancedLocation { + /** + * Adds to the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * In addition to this signature, this method also has the following signatures: + * + * `addAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void;` + * + * @param locationIds The locations to be added to the current list of locations. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + addAsync(locationIds: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Adds to the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * @param locationIds The locations to be added to the current list of locations. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + addAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void; + /** + * Gets the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * In addition to this signature, this method also has the following signatures: + * + * `getAsync(callback?: (result: Office.AsyncResult) => void): void;` + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + getAsync(options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Gets the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + getAsync(callback?: (result: Office.AsyncResult) => void): void; + /** + * Removes the set of locations associated with the appointment. + * + * Any included conference rooms (i.e., in the `LocationDetails` object, the `type` is **ConferenceRoom** and there is an email address) + * should be removed from the locations and the resources lists. + * + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIds. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * In addition to this signature, this method also has the following signatures: + * + * `removeAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void;` + * + * @param locationIds The locations to be removed from the current list of locations. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + removeAsync(locationIds: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Removes the set of locations associated with the appointment. + * + * Any included conference rooms (i.e., in the `LocationDetails` object, the `type` is **ConferenceRoom** and there is an email address) + * should be removed from the locations and the resources lists. + * + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIds. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * @param locationIds The locations to be removed from the current list of locations. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + removeAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void; + } /** * Represents a collection of entities found in an email message or appointment. Read mode only. * @@ -9632,6 +9824,54 @@ declare namespace Office { setAsync(headers: Object, callback?: (result: Office.AsyncResult) => void): void; } + /** + * Represents a location. Read only. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + export interface LocationDetails { + /** + * The location's id. + */ + locationId: LocationIdentifier; + /** + * The location's display name. + */ + displayName: string; + /** + * The email address associated with the location. + */ + emailAddress: string; + /** + * Additional properties for the location. + */ + properties: any; + } + + /** + * Represents the id of a location. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + interface LocationIdentifier { + /** + * The location's unique id. + * + * For **ConferenceRoom** type, it's the room's email address. + * + * For **Custom** type, it's the displayName. + */ + id: string; + /** + * The location's type. + */ + type: MailboxEnums.LocationType; + } + /** * Represents the appointment organizer, even if an alias or a delegate was used to create the appointment. * This object provides a method to get the organizer value of an appointment in an Outlook add-in. @@ -9733,6 +9973,28 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer */ end: Time; + /** + * Gets or sets the locations of the appointment. The `enhancedLocations` property returns an {@link EnhancedLocation} object that + * provides methods to get, remove, or add locations on an item. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
    + * + * @beta + */ + enhancedLocations: EnhancedLocation; /** * Gets the type of item that an instance represents. * @@ -10820,6 +11082,27 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee */ end: Date; + /** + * Gets a set of LocationDetails objects that represents the locations of the appointment. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee
    + * + * @beta + */ + enhancedLocations: LocationDetails[]; /** * Gets the Exchange Web Services item class of the selected item. * From 05763bae96de831c29ba3e052703630fe9454bb4 Mon Sep 17 00:00:00 2001 From: Krzysztof Grzybek Date: Mon, 28 Jan 2019 21:01:19 +0100 Subject: [PATCH 131/312] add text clipper --- types/text-clipper/index.d.ts | 15 +++++++++++++++ types/text-clipper/text-clipper-tests.ts | 5 +++++ types/text-clipper/tsconfig.json | 23 +++++++++++++++++++++++ types/text-clipper/tslint.json | 1 + 4 files changed, 44 insertions(+) create mode 100644 types/text-clipper/index.d.ts create mode 100644 types/text-clipper/text-clipper-tests.ts create mode 100644 types/text-clipper/tsconfig.json create mode 100644 types/text-clipper/tslint.json diff --git a/types/text-clipper/index.d.ts b/types/text-clipper/index.d.ts new file mode 100644 index 0000000000..1f86ac405b --- /dev/null +++ b/types/text-clipper/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for text-clipper 1.2 +// Project: https://github.com/arendjr/text-clipper +// Definitions by: Krzysztof Grzybek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + breakWords?: boolean; + html?: boolean; + imageWeight?: number; + indicator?: string; + maxLines?: number; +} + +declare function clip(string: string, maxLength: number, options?: Options): string; +export = clip; diff --git a/types/text-clipper/text-clipper-tests.ts b/types/text-clipper/text-clipper-tests.ts new file mode 100644 index 0000000000..f4ca7e6f19 --- /dev/null +++ b/types/text-clipper/text-clipper-tests.ts @@ -0,0 +1,5 @@ +import clip = require('text-clipper'); + +clip('text', 123); // $ExpectType string +clip('text', 123, { breakWords: true, html: false }); // $ExpectType string +clip('text', 123, { imageWeight: 123, indicator: 'something', maxLines: 321 }); // $ExpectType string diff --git a/types/text-clipper/tsconfig.json b/types/text-clipper/tsconfig.json new file mode 100644 index 0000000000..caf06929bb --- /dev/null +++ b/types/text-clipper/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", + "text-clipper-tests.ts" + ] +} diff --git a/types/text-clipper/tslint.json b/types/text-clipper/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/text-clipper/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4e27a4d493812771a38368c019bf3720921cb5b3 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 28 Jan 2019 12:12:28 -0800 Subject: [PATCH 132/312] Split node into one file per module --- types/node/assert.d.ts | 52 + types/node/async_hooks.d.ts | 144 + types/node/buffer.d.ts | 6 + types/node/child_process.d.ts | 358 + types/node/cluster.d.ts | 261 + types/node/console.d.ts | 3 + types/node/constants.d.ts | 279 + types/node/crypto.d.ts | 369 + types/node/dgram.d.ts | 97 + types/node/dns.d.ts | 292 + types/node/domain.d.ts | 16 + types/node/events.d.ts | 29 + types/node/fs.d.ts | 2272 ++++ types/node/globals.d.ts | 1031 ++ types/node/http.d.ts | 247 + types/node/http2.d.ts | 861 ++ types/node/https.d.ts | 37 + types/node/index.d.ts | 9223 +---------------- types/node/inspector.d.ts | 1 - types/node/module.d.ts | 3 + types/node/net.d.ts | 251 + types/node/os.d.ts | 192 + types/node/path.d.ts | 159 + types/node/perf_hooks.d.ts | 241 + types/node/process.d.ts | 3 + types/node/punycode.d.ts | 12 + types/node/querystring.d.ts | 17 + types/node/readline.d.ts | 135 + types/node/repl.d.ts | 372 + .../inspector.d.ts.template | 1 - types/node/stream.d.ts | 294 + types/node/string_decoder.d.ts | 9 + types/node/timers.d.ts | 16 + types/node/tls.d.ts | 371 + types/node/trace_events.d.ts | 61 + types/node/tsconfig.json | 39 + types/node/tslint.json | 1 + types/node/tty.d.ts | 15 + types/node/url.d.ts | 104 + types/node/util.d.ts | 173 + types/node/v8.d.ts | 28 + types/node/vm.d.ts | 64 + types/node/worker_threads.d.ts | 124 + types/node/zlib.d.ts | 138 + 44 files changed, 9216 insertions(+), 9185 deletions(-) create mode 100644 types/node/assert.d.ts create mode 100644 types/node/async_hooks.d.ts create mode 100644 types/node/buffer.d.ts create mode 100644 types/node/child_process.d.ts create mode 100644 types/node/cluster.d.ts create mode 100644 types/node/console.d.ts create mode 100644 types/node/constants.d.ts create mode 100644 types/node/crypto.d.ts create mode 100644 types/node/dgram.d.ts create mode 100644 types/node/dns.d.ts create mode 100644 types/node/domain.d.ts create mode 100644 types/node/events.d.ts create mode 100644 types/node/fs.d.ts create mode 100644 types/node/globals.d.ts create mode 100644 types/node/http.d.ts create mode 100644 types/node/http2.d.ts create mode 100644 types/node/https.d.ts create mode 100644 types/node/module.d.ts create mode 100644 types/node/net.d.ts create mode 100644 types/node/os.d.ts create mode 100644 types/node/path.d.ts create mode 100644 types/node/perf_hooks.d.ts create mode 100644 types/node/process.d.ts create mode 100644 types/node/punycode.d.ts create mode 100644 types/node/querystring.d.ts create mode 100644 types/node/readline.d.ts create mode 100644 types/node/repl.d.ts create mode 100644 types/node/stream.d.ts create mode 100644 types/node/string_decoder.d.ts create mode 100644 types/node/timers.d.ts create mode 100644 types/node/tls.d.ts create mode 100644 types/node/trace_events.d.ts create mode 100644 types/node/tty.d.ts create mode 100644 types/node/url.d.ts create mode 100644 types/node/util.d.ts create mode 100644 types/node/v8.d.ts create mode 100644 types/node/vm.d.ts create mode 100644 types/node/worker_threads.d.ts create mode 100644 types/node/zlib.d.ts diff --git a/types/node/assert.d.ts b/types/node/assert.d.ts new file mode 100644 index 0000000000..d73353c5d8 --- /dev/null +++ b/types/node/assert.d.ts @@ -0,0 +1,52 @@ +declare module "assert" { + function internal(value: any, message?: string | Error): void; + namespace internal { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: Function, message?: string | Error): void; + function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: Function, message?: string | Error): void; + function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: Function | Promise, message?: string | Error): Promise; + function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; + + const strict: typeof internal; + } + + export = internal; +} diff --git a/types/node/async_hooks.d.ts b/types/node/async_hooks.d.ts new file mode 100644 index 0000000000..2c77932ecd --- /dev/null +++ b/types/node/async_hooks.d.ts @@ -0,0 +1,144 @@ +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} diff --git a/types/node/buffer.d.ts b/types/node/buffer.d.ts new file mode 100644 index 0000000000..86fdfdb36c --- /dev/null +++ b/types/node/buffer.d.ts @@ -0,0 +1,6 @@ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + const SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} diff --git a/types/node/child_process.d.ts b/types/node/child_process.d.ts new file mode 100644 index 0000000000..c8d20b8249 --- /dev/null +++ b/types/node/child_process.d.ts @@ -0,0 +1,358 @@ +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + killed: boolean; + pid: number; + kill(signal?: string): void; + send(message: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + + interface SpawnOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + + function spawn(command: string, options?: SpawnOptions): ChildProcess; + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; + + interface ExecOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ({ encoding?: string | null } & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + windowsVerbatimArguments?: boolean; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: string[] | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + windowsVerbatimArguments?: boolean; + uid?: number; + gid?: number; + } + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions { + argv0?: string; // Not specified in the docs + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} diff --git a/types/node/cluster.d.ts b/types/node/cluster.d.ts new file mode 100644 index 0000000000..2bfe353140 --- /dev/null +++ b/types/node/cluster.d.ts @@ -0,0 +1,261 @@ +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + } + + function disconnect(callback?: Function): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + // TODO: cluster.schedulingPolicy + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: any): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: any) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: any) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + function eventNames(): string[]; +} diff --git a/types/node/console.d.ts b/types/node/console.d.ts new file mode 100644 index 0000000000..d30d13f871 --- /dev/null +++ b/types/node/console.d.ts @@ -0,0 +1,3 @@ +declare module "console" { + export = console; +} diff --git a/types/node/constants.d.ts b/types/node/constants.d.ts new file mode 100644 index 0000000000..6c39d64346 --- /dev/null +++ b/types/node/constants.d.ts @@ -0,0 +1,279 @@ +declare module "constants" { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + const SIGHUP: number; + const SIGINT: number; + const SIGILL: number; + const SIGABRT: number; + const SIGFPE: number; + const SIGKILL: number; + const SIGSEGV: number; + const SIGTERM: number; + const SIGBREAK: number; + const SIGWINCH: number; + const SSL_OP_ALL: number; + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + const SSL_OP_CISCO_ANYCONNECT: number; + const SSL_OP_COOKIE_EXCHANGE: number; + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + const SSL_OP_EPHEMERAL_RSA: number; + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + const SSL_OP_SINGLE_DH_USE: number; + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_ECDH: number; + const ENGINE_METHOD_ECDSA: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_STORE: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const NPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + const O_RDONLY: number; + const O_WRONLY: number; + const O_RDWR: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFDIR: number; + const S_IFCHR: number; + const S_IFBLK: number; + const S_IFIFO: number; + const S_IFSOCK: number; + const S_IRWXU: number; + const S_IRUSR: number; + const S_IWUSR: number; + const S_IXUSR: number; + const S_IRWXG: number; + const S_IRGRP: number; + const S_IWGRP: number; + const S_IXGRP: number; + const S_IRWXO: number; + const S_IROTH: number; + const S_IWOTH: number; + const S_IXOTH: number; + const S_IFLNK: number; + const O_CREAT: number; + const O_EXCL: number; + const O_NOCTTY: number; + const O_DIRECTORY: number; + const O_NOATIME: number; + const O_NOFOLLOW: number; + const O_SYNC: number; + const O_DSYNC: number; + const O_SYMLINK: number; + const O_DIRECT: number; + const O_NONBLOCK: number; + const O_TRUNC: number; + const O_APPEND: number; + const F_OK: number; + const R_OK: number; + const W_OK: number; + const X_OK: number; + const COPYFILE_EXCL: number; + const COPYFILE_FICLONE: number; + const COPYFILE_FICLONE_FORCE: number; + const UV_UDP_REUSEADDR: number; + const SIGQUIT: number; + const SIGTRAP: number; + const SIGIOT: number; + const SIGBUS: number; + const SIGUSR1: number; + const SIGUSR2: number; + const SIGPIPE: number; + const SIGALRM: number; + const SIGCHLD: number; + const SIGSTKFLT: number; + const SIGCONT: number; + const SIGSTOP: number; + const SIGTSTP: number; + const SIGTTIN: number; + const SIGTTOU: number; + const SIGURG: number; + const SIGXCPU: number; + const SIGXFSZ: number; + const SIGVTALRM: number; + const SIGPROF: number; + const SIGIO: number; + const SIGPOLL: number; + const SIGPWR: number; + const SIGSYS: number; + const SIGUNUSED: number; + const defaultCoreCipherList: string; + const defaultCipherList: string; + const ENGINE_METHOD_RSA: number; + const ALPN_ENABLED: number; +} diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts new file mode 100644 index 0000000000..0d37716a7e --- /dev/null +++ b/types/node/crypto.d.ts @@ -0,0 +1,369 @@ +declare module "crypto" { + import * as stream from "stream"; + + interface Certificate { + exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; + } + const Certificate: { + new(): Certificate; + (): Certificate; + }; + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + interface Credentials { context?: any; } + function createCredentials(details: CredentialDetails): Credentials; + function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + interface Cipher extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + // second arg ignored + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + // second arg is ignored + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; + // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; + } + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; + } + function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; + verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomFillSync(buffer: T, offset?: number, size?: number): T; + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: string; + padding?: number; + } + interface RsaPrivateKey { + key: string; + passphrase?: string; + padding?: number; + } + function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getHashes(): string[]; + class ECDH { + static convertKey( + key: string | Buffer | NodeJS.TypedArray | DataView, + curve: string, + inputEncoding?: HexBase64Latin1Encoding, + outputEncoding?: "latin1" | "hex" | "base64", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + } +} diff --git a/types/node/dgram.d.ts b/types/node/dgram.d.ts new file mode 100644 index 0000000000..48049b47b8 --- /dev/null +++ b/types/node/dgram.d.ts @@ -0,0 +1,97 @@ +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: string; + port: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } +} diff --git a/types/node/dns.d.ts b/types/node/dns.d.ts new file mode 100644 index 0000000000..a77216f797 --- /dev/null +++ b/types/node/dns.d.ts @@ -0,0 +1,292 @@ +declare module "dns" { + // Supported getaddrinfo flags. + const ADDRCONFIG: number; + const V4MAPPED: number; + + interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + interface LookupOneOptions extends LookupOptions { + all?: false; + } + + interface LookupAllOptions extends LookupOptions { + all: true; + } + + interface LookupAddress { + address: string; + family: number; + } + + function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; + + namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + interface ResolveOptions { + ttl: boolean; + } + + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + interface MxRecord { + priority: number; + exchange: string; + } + + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + interface AnyNsRecord { + type: "NS"; + value: string; + } + + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + + function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + + function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + function setServers(servers: string[]): void; + function getServers(): string[]; + + // Error codes + const NODATA: string; + const FORMERR: string; + const SERVFAIL: string; + const NOTFOUND: string; + const NOTIMP: string; + const REFUSED: string; + const BADQUERY: string; + const BADNAME: string; + const BADFAMILY: string; + const BADRESP: string; + const CONNREFUSED: string; + const TIMEOUT: string; + const EOF: string; + const FILE: string; + const NOMEM: string; + const DESTRUCTION: string; + const BADSTR: string; + const BADFLAGS: string; + const NONAME: string; + const BADHINTS: string; + const NOTINITIALIZED: string; + const LOADIPHLPAPI: string; + const ADDRGETNETWORKPARAMS: string; + const CANCELLED: string; + + class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } +} diff --git a/types/node/domain.d.ts b/types/node/domain.d.ts new file mode 100644 index 0000000000..6a30decfa5 --- /dev/null +++ b/types/node/domain.d.ts @@ -0,0 +1,16 @@ +declare module "domain" { + import * as events from "events"; + + class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + members: any[]; + enter(): void; + exit(): void; + } + + function create(): Domain; +} diff --git a/types/node/events.d.ts b/types/node/events.d.ts new file mode 100644 index 0000000000..dd0d8d191b --- /dev/null +++ b/types/node/events.d.ts @@ -0,0 +1,29 @@ +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} diff --git a/types/node/fs.d.ts b/types/node/fs.d.ts new file mode 100644 index 0000000000..e3718475e5 --- /dev/null +++ b/types/node/fs.d.ts @@ -0,0 +1,2272 @@ +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type BinaryData = Buffer | DataView | NodeJS.TypedArray; + class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + } +} diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts new file mode 100644 index 0000000000..e4f6f40fd1 --- /dev/null +++ b/types/node/globals.d.ts @@ -0,0 +1,1031 @@ +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// compat for TypeScript 1.8 and default es5 target +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } + +interface Set {} +interface ReadonlySet {} + +// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IteratorResult { } +interface IterableIterator { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly observable: symbol; + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare const SlowBuffer: { + new(str: string, encoding?: string): Buffer; + new(size: number): Buffer; + new(size: Uint8Array): Buffer; + new(array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare const Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean | undefined; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + showHidden?: boolean; + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + interface Process extends EventEmitter { + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Immediate { + ref(): void; + unref(): void; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} diff --git a/types/node/http.d.ts b/types/node/http.d.ts new file mode 100644 index 0000000000..e5f3741003 --- /dev/null +++ b/types/node/http.d.ts @@ -0,0 +1,247 @@ +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + import { URL } from "url"; + + // incoming headers will never contain number + interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; + } + + class Server extends net.Server { + constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + maxHeadersCount: number; + timeout: number; + keepAliveTimeout: number; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + abort(): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; +} diff --git a/types/node/http2.d.ts b/types/node/http2.d.ts new file mode 100644 index 0000000000..aecbca783f --- /dev/null +++ b/types/node/http2.d.ts @@ -0,0 +1,861 @@ +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + streamLocalClose?: number; + streamRemoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + readonly closed: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + + sendTrailers(headers: OutgoingHttpHeaders): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends events.EventEmitter { + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + rstStream(stream: Http2Stream, code?: number): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + priority(stream: Http2Stream, options: StreamPriorityOptions): void; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxReservedRemoteStreams?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; + } + + export type ClientSessionOptions = SessionOptions; + export type ServerSessionOptions = SessionOptions; + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface Http2Server extends net.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface Http2SecureServer extends tls.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + private constructor(); + headers: IncomingHttpHeaders; + httpVersion: string; + method: string; + rawHeaders: string[]; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + stream: ServerHttp2Stream; + trailers: IncomingHttpHeaders; + url: string; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + } + + export class Http2ServerResponse extends events.EventEmitter { + private constructor(); + addTrailers(trailers: OutgoingHttpHeaders): void; + connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data?: string | Buffer, callback?: () => void): void; + end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | string[]): void; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + stream: ServerHttp2Stream; + write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Settings; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} diff --git a/types/node/https.d.ts b/types/node/https.d.ts new file mode 100644 index 0000000000..c9bc7c5f63 --- /dev/null +++ b/types/node/https.d.ts @@ -0,0 +1,37 @@ +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + class Server extends tls.Server { + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + timeout: number; + keepAliveTimeout: number; + } + + function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} diff --git a/types/node/index.d.ts b/types/node/index.d.ts index c63b6c892b..48d1b5873c 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -34,9186 +34,43 @@ // Samuel Ainsworth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** inspector module types */ -/// - -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * The console.markTimeline() method is the deprecated form of console.timeStamp(). - * - * @deprecated Use console.timeStamp() instead. - */ - markTimeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timeline() method is the deprecated form of console.time(). - * - * @deprecated Use console.time() instead. - */ - timeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timelineEnd() method is the deprecated form of console.timeEnd(). - * - * @deprecated Use console.timeEnd() instead. - */ - timelineEnd(label?: string): void; -} - -interface Error { - stack?: string; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -// compat for TypeScript 1.8 and default es5 target -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - -interface Set {} -interface ReadonlySet {} - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IteratorResult { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly observable: symbol; - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -interface NodeRequireFunction { - /* tslint:disable-next-line:callable-types */ - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve: RequireResolve; - cache: any; - extensions: NodeExtensions; - main: NodeModule | undefined; -} - -interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; -} - -interface NodeExtensions { - '.js': (m: NodeModule, filename: string) => any; - '.json': (m: NodeModule, filename: string) => any; - '.node': (m: NodeModule, filename: string) => any; - [ext: string]: (m: NodeModule, filename: string) => any; -} - -declare var require: NodeRequire; - -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: NodeModule | null; - children: NodeModule[]; - paths: string[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; -declare const SlowBuffer: { - new(str: string, encoding?: string): Buffer; - new(size: number): Buffer; - new(size: Uint8Array): Buffer; - new(array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends Uint8Array { - constructor: typeof Buffer; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Uint8Array): boolean; - compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare const Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - new(str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - new(size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - new(buffer: Buffer): Buffer; - prototype: Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() - */ - from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - from(data: any[]): Buffer; - from(data: Uint8Array): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - */ - from(str: string, encoding?: string): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - of(...items: number[]): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean | undefined; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - concat(list: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Uint8Array, buf2: Uint8Array): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - poolSize: number; -}; - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - showHidden?: boolean; - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - breakLength?: number; - compact?: boolean; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - class EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(cb?: Function): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Events extends EventEmitter { } - - interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: any, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - interface ProcessEnv { - [key: string]: string | undefined; - } - - interface WriteStream extends Socket { - readonly writableHighWaterMark: number; - readonly writableLength: number; - columns?: number; - rows?: number; - _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error | null, callback: Function): void; - _final(callback: Function): void; - setDefaultEncoding(encoding: string): this; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - } - interface ReadStream extends Socket { - readonly readableHighWaterMark: number; - readonly readableLength: number; - isRaw?: boolean; - setRawMode?(mode: boolean): void; - _read(size: number): void; - _destroy(err: Error | null, callback: Function): void; - push(chunk: any, encoding?: string): boolean; - destroy(error?: Error): void; - } - - interface Process extends EventEmitter { - stdout: WriteStream; - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * EventEmitter - * 1. beforeExit - * 2. disconnect - * 3. exit - * 4. message - * 5. rejectionHandled - * 6. uncaughtException - * 7. unhandledRejection - * 8. warning - * 9. message - * 10. - * 11. newListener/removeListener inherited from EventEmitter - */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface Timer { - ref(): void; - refresh(): void; - unref(): void; - } - - class Immediate { - ref(): void; - unref(): void; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - class Timeout implements Timer { - ref(): void; - refresh(): void; - unref(): void; - } - - class Module { - static runMain(): void; - static wrap(code: string): string; - static createRequireFromPath(path: string): (path: string) => any; - static builtinModules: string[]; - - static Module: typeof Module; - - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: Module | null; - children: Module[]; - paths: string[]; - - constructor(id: string, parent?: Module); - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; -} - -interface IterableIterator { } - -/*----------------------------------------------* -* * -* MODULES * -* * -*-----------------------------------------------*/ -declare module "buffer" { - export const INSPECT_MAX_BYTES: number; - const BuffType: typeof Buffer; - const SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; -} - -declare module "querystring" { - interface StringifyOptions { - encodeURIComponent?: Function; - } - - interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } - - interface ParsedUrlQuery { [key: string]: string | string[]; } - - function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; - function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; - function escape(str: string): string; - function unescape(str: string): string; -} - -declare module "events" { - class internal extends NodeJS.EventEmitter { } - - namespace internal { - class EventEmitter extends internal { - /** @deprecated since v4.0.0 */ - static listenerCount(emitter: EventEmitter, event: string | symbol): number; - static defaultMaxListeners: number; - - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): Array; - listenerCount(type: string | symbol): number; - } - } - - export = internal; -} - -declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; - import { URL } from "url"; - - // incoming headers will never contain number - interface IncomingHttpHeaders { - 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; - 'accept-patch'?: string; - 'accept-ranges'?: string; - 'age'?: string; - 'allow'?: string; - 'alt-svc'?: string; - 'authorization'?: string; - 'cache-control'?: string; - 'connection'?: string; - 'content-disposition'?: string; - 'content-encoding'?: string; - 'content-language'?: string; - 'content-length'?: string; - 'content-location'?: string; - 'content-range'?: string; - 'content-type'?: string; - 'cookie'?: string; - 'date'?: string; - 'expect'?: string; - 'expires'?: string; - 'forwarded'?: string; - 'from'?: string; - 'host'?: string; - 'if-match'?: string; - 'if-modified-since'?: string; - 'if-none-match'?: string; - 'if-unmodified-since'?: string; - 'last-modified'?: string; - 'location'?: string; - 'pragma'?: string; - 'proxy-authenticate'?: string; - 'proxy-authorization'?: string; - 'public-key-pins'?: string; - 'range'?: string; - 'referer'?: string; - 'retry-after'?: string; - 'set-cookie'?: string[]; - 'strict-transport-security'?: string; - 'trailer'?: string; - 'transfer-encoding'?: string; - 'tk'?: string; - 'upgrade'?: string; - 'user-agent'?: string; - 'vary'?: string; - 'via'?: string; - 'warning'?: string; - 'www-authenticate'?: string; - [header: string]: string | string[] | undefined; - } - - // outgoing headers allows numbers (as they are converted internally to strings) - interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; - } - - interface ClientRequestArgs { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number | string; - defaultPort?: number | string; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: OutgoingHttpHeaders; - auth?: string; - agent?: Agent | boolean; - _defaultAgent?: Agent; - timeout?: number; - setHost?: boolean; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; - } - - class Server extends net.Server { - constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); - - setTimeout(msecs?: number, callback?: () => void): this; - setTimeout(callback: () => void): this; - maxHeadersCount: number; - timeout: number; - keepAliveTimeout: number; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js - class OutgoingMessage extends stream.Writable { - upgrading: boolean; - chunkedEncoding: boolean; - shouldKeepAlive: boolean; - useChunkedEncodingByDefault: boolean; - sendDate: boolean; - finished: boolean; - headersSent: boolean; - connection: net.Socket; - - constructor(); - - setTimeout(msecs: number, callback?: () => void): this; - setHeader(name: string, value: number | string | string[]): void; - getHeader(name: string): number | string | string[] | undefined; - getHeaders(): OutgoingHttpHeaders; - getHeaderNames(): string[]; - hasHeader(name: string): boolean; - removeHeader(name: string): void; - addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; - flushHeaders(): void; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 - class ServerResponse extends OutgoingMessage { - statusCode: number; - statusMessage: string; - - constructor(req: IncomingMessage); - - assignSocket(socket: net.Socket): void; - detachSocket(socket: net.Socket): void; - // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 - // no args in writeContinue callback - writeContinue(callback?: () => void): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 - class ClientRequest extends OutgoingMessage { - connection: net.Socket; - socket: net.Socket; - aborted: number; - - constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); - - abort(): void; - onSocket(socket: net.Socket): void; - setTimeout(timeout: number, callback?: () => void): this; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - } - - class IncomingMessage extends stream.Readable { - constructor(socket: net.Socket); - - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - connection: net.Socket; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - trailers: { [key: string]: string | undefined }; - rawTrailers: string[]; - setTimeout(msecs: number, callback: () => void): this; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - destroy(error?: Error): void; - } - - interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - /** - * Socket timeout in milliseconds. This will set the timeout after the socket is connected. - */ - timeout?: number; - } - - class Agent { - maxFreeSockets: number; - maxSockets: number; - sockets: any; - requests: any; - - constructor(opts?: AgentOptions); - - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } - - const METHODS: string[]; - - const STATUS_CODES: { - [errorCode: number]: string | undefined; - [errorCode: string]: string | undefined; - }; - - function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - function createClient(port?: number, host?: string): any; - - // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, - // create interface RequestOptions would make the naming more clear to developers - interface RequestOptions extends ClientRequestArgs { } - function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - let globalAgent: Agent; -} - -declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; - - // interfaces - interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv - exec?: string; - args?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - inspectPort?: number | (() => number); - } - - interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } - - class Worker extends events.EventEmitter { - id: number; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; - - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "listening", address: Address): boolean; - emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - - interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: Function): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - // TODO: cluster.schedulingPolicy - settings: ClusterSettings; - setupMaster(settings?: ClusterSettings): void; - worker?: Worker; - workers?: { - [index: string]: Worker | undefined - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: any) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect", worker: Worker): boolean; - emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - emit(event: "fork", worker: Worker): boolean; - emit(event: "listening", worker: Worker, address: Address): boolean; - emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online", worker: Worker): boolean; - emit(event: "setup", settings: any): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: any) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: any) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: any) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: any) => void): this; - } - - function disconnect(callback?: Function): void; - function fork(env?: any): Worker; - const isMaster: boolean; - const isWorker: boolean; - // TODO: cluster.schedulingPolicy - const settings: ClusterSettings; - function setupMaster(settings?: ClusterSettings): void; - const worker: Worker; - const workers: { - [index: string]: Worker | undefined - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - function addListener(event: string, listener: (...args: any[]) => void): Cluster; - function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - function addListener(event: "setup", listener: (settings: any) => void): Cluster; - - function emit(event: string | symbol, ...args: any[]): boolean; - function emit(event: "disconnect", worker: Worker): boolean; - function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - function emit(event: "fork", worker: Worker): boolean; - function emit(event: "listening", worker: Worker, address: Address): boolean; - function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - function emit(event: "online", worker: Worker): boolean; - function emit(event: "setup", settings: any): boolean; - - function on(event: string, listener: (...args: any[]) => void): Cluster; - function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function on(event: "fork", listener: (worker: Worker) => void): Cluster; - function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - function on(event: "online", listener: (worker: Worker) => void): Cluster; - function on(event: "setup", listener: (settings: any) => void): Cluster; - - function once(event: string, listener: (...args: any[]) => void): Cluster; - function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function once(event: "fork", listener: (worker: Worker) => void): Cluster; - function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - function once(event: "online", listener: (worker: Worker) => void): Cluster; - function once(event: "setup", listener: (settings: any) => void): Cluster; - - function removeListener(event: string, listener: (...args: any[]) => void): Cluster; - function removeAllListeners(event?: string): Cluster; - function setMaxListeners(n: number): Cluster; - function getMaxListeners(): number; - function listeners(event: string): Function[]; - function listenerCount(type: string): number; - - function prependListener(event: string, listener: (...args: any[]) => void): Cluster; - function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - - function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; - function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; - - function eventNames(): string[]; -} - -declare module "worker_threads" { - import { EventEmitter } from "events"; - import { Readable, Writable } from "stream"; - - const isMainThread: boolean; - const parentPort: null | MessagePort; - const threadId: number; - const workerData: any; - - class MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; - } - - class MessagePort extends EventEmitter { - close(): void; - postMessage(value: any, transferList?: Array): void; - ref(): void; - unref(): void; - start(): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "message", listener: (value: any) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "message", value: any): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "message", listener: (value: any) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "message", listener: (value: any) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - } - - interface WorkerOptions { - eval?: boolean; - workerData?: any; - stdin?: boolean; - stdout?: boolean; - stderr?: boolean; - } - - class Worker extends EventEmitter { - readonly stdin: Writable | null; - readonly stdout: Readable; - readonly stderr: Readable; - readonly threadId: number; - - constructor(filename: string, options?: WorkerOptions); - - postMessage(value: any, transferList?: Array): void; - ref(): void; - unref(): void; - terminate(callback?: (err: any, exitCode: number) => void): void; - - addListener(event: "error", listener: (err: any) => void): this; - addListener(event: "exit", listener: (exitCode: number) => void): this; - addListener(event: "message", listener: (value: any) => void): this; - addListener(event: "online", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "error", err: any): boolean; - emit(event: "exit", exitCode: number): boolean; - emit(event: "message", value: any): boolean; - emit(event: "online"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "error", listener: (err: any) => void): this; - on(event: "exit", listener: (exitCode: number) => void): this; - on(event: "message", listener: (value: any) => void): this; - on(event: "online", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "error", listener: (err: any) => void): this; - once(event: "exit", listener: (exitCode: number) => void): this; - once(event: "message", listener: (value: any) => void): this; - once(event: "online", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "error", listener: (err: any) => void): this; - prependListener(event: "exit", listener: (exitCode: number) => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "online", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "error", listener: (err: any) => void): this; - prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "online", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "error", listener: (err: any) => void): this; - removeListener(event: "exit", listener: (exitCode: number) => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "online", listener: () => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - off(event: "error", listener: (err: any) => void): this; - off(event: "exit", listener: (exitCode: number) => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "online", listener: () => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - } -} - -declare module "zlib" { - import * as stream from "stream"; - - interface ZlibOptions { - flush?: number; // default: zlib.constants.Z_NO_FLUSH - finishFlush?: number; // default: zlib.constants.Z_FINISH - chunkSize?: number; // default: 16*1024 - windowBits?: number; - level?: number; // compression only - memLevel?: number; // compression only - strategy?: number; // compression only - dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default - } - - interface Zlib { - readonly bytesRead: number; - close(callback?: () => void): void; - flush(kind?: number | (() => void), callback?: () => void): void; - } - - interface ZlibParams { - params(level: number, strategy: number, callback: () => void): void; - } - - interface ZlibReset { - reset(): void; - } - - interface Gzip extends stream.Transform, Zlib { } - interface Gunzip extends stream.Transform, Zlib { } - interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - interface Inflate extends stream.Transform, Zlib, ZlibReset { } - interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } - interface Unzip extends stream.Transform, Zlib { } - - function createGzip(options?: ZlibOptions): Gzip; - function createGunzip(options?: ZlibOptions): Gunzip; - function createDeflate(options?: ZlibOptions): Deflate; - function createInflate(options?: ZlibOptions): Inflate; - function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - function createInflateRaw(options?: ZlibOptions): InflateRaw; - function createUnzip(options?: ZlibOptions): Unzip; - - type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; - function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; - - namespace constants { - // Allowed flush values. - - const Z_NO_FLUSH: number; - const Z_PARTIAL_FLUSH: number; - const Z_SYNC_FLUSH: number; - const Z_FULL_FLUSH: number; - const Z_FINISH: number; - const Z_BLOCK: number; - const Z_TREES: number; - - // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. - - const Z_OK: number; - const Z_STREAM_END: number; - const Z_NEED_DICT: number; - const Z_ERRNO: number; - const Z_STREAM_ERROR: number; - const Z_DATA_ERROR: number; - const Z_MEM_ERROR: number; - const Z_BUF_ERROR: number; - const Z_VERSION_ERROR: number; - - // Compression levels. - - const Z_NO_COMPRESSION: number; - const Z_BEST_SPEED: number; - const Z_BEST_COMPRESSION: number; - const Z_DEFAULT_COMPRESSION: number; - - // Compression strategy. - - const Z_FILTERED: number; - const Z_HUFFMAN_ONLY: number; - const Z_RLE: number; - const Z_FIXED: number; - const Z_DEFAULT_STRATEGY: number; - } - - // Constants - const Z_NO_FLUSH: number; - const Z_PARTIAL_FLUSH: number; - const Z_SYNC_FLUSH: number; - const Z_FULL_FLUSH: number; - const Z_FINISH: number; - const Z_BLOCK: number; - const Z_TREES: number; - const Z_OK: number; - const Z_STREAM_END: number; - const Z_NEED_DICT: number; - const Z_ERRNO: number; - const Z_STREAM_ERROR: number; - const Z_DATA_ERROR: number; - const Z_MEM_ERROR: number; - const Z_BUF_ERROR: number; - const Z_VERSION_ERROR: number; - const Z_NO_COMPRESSION: number; - const Z_BEST_SPEED: number; - const Z_BEST_COMPRESSION: number; - const Z_DEFAULT_COMPRESSION: number; - const Z_FILTERED: number; - const Z_HUFFMAN_ONLY: number; - const Z_RLE: number; - const Z_FIXED: number; - const Z_DEFAULT_STRATEGY: number; - const Z_BINARY: number; - const Z_TEXT: number; - const Z_ASCII: number; - const Z_UNKNOWN: number; - const Z_DEFLATED: number; -} - -declare module "os" { - interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - interface NetworkInterfaceBase { - address: string; - netmask: string; - mac: string; - internal: boolean; - cidr: string | null; - } - - interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; - } - - interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; - scopeid: number; - } - - type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; - - function hostname(): string; - function loadavg(): number[]; - function uptime(): number; - function freemem(): number; - function totalmem(): number; - function cpus(): CpuInfo[]; - function type(): string; - function release(): string; - function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - function homedir(): string; - function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; - const constants: { - UV_UDP_REUSEADDR: number; - signals: { - SIGHUP: number; - SIGINT: number; - SIGQUIT: number; - SIGILL: number; - SIGTRAP: number; - SIGABRT: number; - SIGIOT: number; - SIGBUS: number; - SIGFPE: number; - SIGKILL: number; - SIGUSR1: number; - SIGSEGV: number; - SIGUSR2: number; - SIGPIPE: number; - SIGALRM: number; - SIGTERM: number; - SIGCHLD: number; - SIGSTKFLT: number; - SIGCONT: number; - SIGSTOP: number; - SIGTSTP: number; - SIGTTIN: number; - SIGTTOU: number; - SIGURG: number; - SIGXCPU: number; - SIGXFSZ: number; - SIGVTALRM: number; - SIGPROF: number; - SIGWINCH: number; - SIGIO: number; - SIGPOLL: number; - SIGPWR: number; - SIGSYS: number; - SIGUNUSED: number; - }; - errno: { - E2BIG: number; - EACCES: number; - EADDRINUSE: number; - EADDRNOTAVAIL: number; - EAFNOSUPPORT: number; - EAGAIN: number; - EALREADY: number; - EBADF: number; - EBADMSG: number; - EBUSY: number; - ECANCELED: number; - ECHILD: number; - ECONNABORTED: number; - ECONNREFUSED: number; - ECONNRESET: number; - EDEADLK: number; - EDESTADDRREQ: number; - EDOM: number; - EDQUOT: number; - EEXIST: number; - EFAULT: number; - EFBIG: number; - EHOSTUNREACH: number; - EIDRM: number; - EILSEQ: number; - EINPROGRESS: number; - EINTR: number; - EINVAL: number; - EIO: number; - EISCONN: number; - EISDIR: number; - ELOOP: number; - EMFILE: number; - EMLINK: number; - EMSGSIZE: number; - EMULTIHOP: number; - ENAMETOOLONG: number; - ENETDOWN: number; - ENETRESET: number; - ENETUNREACH: number; - ENFILE: number; - ENOBUFS: number; - ENODATA: number; - ENODEV: number; - ENOENT: number; - ENOEXEC: number; - ENOLCK: number; - ENOLINK: number; - ENOMEM: number; - ENOMSG: number; - ENOPROTOOPT: number; - ENOSPC: number; - ENOSR: number; - ENOSTR: number; - ENOSYS: number; - ENOTCONN: number; - ENOTDIR: number; - ENOTEMPTY: number; - ENOTSOCK: number; - ENOTSUP: number; - ENOTTY: number; - ENXIO: number; - EOPNOTSUPP: number; - EOVERFLOW: number; - EPERM: number; - EPIPE: number; - EPROTO: number; - EPROTONOSUPPORT: number; - EPROTOTYPE: number; - ERANGE: number; - EROFS: number; - ESPIPE: number; - ESRCH: number; - ESTALE: number; - ETIME: number; - ETIMEDOUT: number; - ETXTBSY: number; - EWOULDBLOCK: number; - EXDEV: number; - }; - priority: { - PRIORITY_LOW: number; - PRIORITY_BELOW_NORMAL: number; - PRIORITY_NORMAL: number; - PRIORITY_ABOVE_NORMAL: number; - PRIORITY_HIGH: number; - PRIORITY_HIGHEST: number; - } - }; - function arch(): string; - function platform(): NodeJS.Platform; - function tmpdir(): string; - const EOL: string; - function endianness(): "BE" | "LE"; - /** - * Gets the priority of a process. - * Defaults to current process. - */ - function getPriority(pid?: number): number; - /** - * Sets the priority of the current process. - * @param priority Must be in range of -20 to 19 - */ - function setPriority(priority: number): void; - /** - * Sets the priority of the process specified process. - * @param priority Must be in range of -20 to 19 - */ - function setPriority(pid: number, priority: number): void; -} - -declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; - import { URL } from "url"; - - type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; - - type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { - rejectUnauthorized?: boolean; // Defaults to true - servername?: string; // SNI TLS Extension - }; - - interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { - rejectUnauthorized?: boolean; - maxCachedSessions?: number; - } - - class Agent extends http.Agent { - constructor(options?: AgentOptions); - options: AgentOptions; - } - - class Server extends tls.Server { - setTimeout(callback: () => void): this; - setTimeout(msecs?: number, callback?: () => void): this; - timeout: number; - keepAliveTimeout: number; - } - - function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; - function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - let globalAgent: Agent; -} - -declare module "punycode" { - function decode(string: string): string; - function encode(string: string): string; - function toUnicode(domain: string): string; - function toASCII(domain: string): string; - const ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - const version: any; -} - -declare module "repl" { - import { Interface, Completer, AsyncCompleter } from "readline"; - import { Context } from "vm"; - import { InspectOptions } from "util"; - - interface ReplOptions { - /** - * The input prompt to display. - * Default: `"> "` - */ - prompt?: string; - /** - * The `Readable` stream from which REPL input will be read. - * Default: `process.stdin` - */ - input?: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - * Default: `process.stdout` - */ - output?: NodeJS.WritableStream; - /** - * If `true`, specifies that the output should be treated as a TTY terminal, and have - * ANSI/VT100 escape codes written to it. - * Default: checking the value of the `isTTY` property on the output stream upon - * instantiation. - */ - terminal?: boolean; - /** - * The function to be used when evaluating each given line of input. - * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can - * error with `repl.Recoverable` to indicate the input was incomplete and prompt for - * additional lines. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions - */ - eval?: REPLEval; - /** - * If `true`, specifies that the default `writer` function should include ANSI color - * styling to REPL output. If a custom `writer` function is provided then this has no - * effect. - * Default: the REPL instance's `terminal` value. - */ - useColors?: boolean; - /** - * If `true`, specifies that the default evaluation function will use the JavaScript - * `global` as the context as opposed to creating a new separate context for the REPL - * instance. The node CLI REPL sets this value to `true`. - * Default: `false`. - */ - useGlobal?: boolean; - /** - * If `true`, specifies that the default writer will not output the return value of a - * command if it evaluates to `undefined`. - * Default: `false`. - */ - ignoreUndefined?: boolean; - /** - * The function to invoke to format the output of each command before writing to `output`. - * Default: a wrapper for `util.inspect`. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output - */ - writer?: REPLWriter; - /** - * An optional function used for custom Tab auto completion. - * - * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function - */ - completer?: Completer | AsyncCompleter; - /** - * A flag that specifies whether the default evaluator executes all JavaScript commands in - * strict mode or default (sloppy) mode. - * Accepted values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - /** - * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is - * pressed. This cannot be used together with a custom `eval` function. - * Default: `false`. - */ - breakEvalOnSigint?: boolean; - } - - type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; - type REPLWriter = (this: REPLServer, obj: any) => string; - - /** - * This is the default "writer" value, if none is passed in the REPL options, - * and it can be overridden by custom print functions. - */ - const writer: REPLWriter & { options: InspectOptions }; - - type REPLCommandAction = (this: REPLServer, text: string) => void; - - interface REPLCommand { - /** - * Help text to be displayed when `.help` is entered. - */ - help?: string; - /** - * The function to execute, optionally accepting a single string argument. - */ - action: REPLCommandAction; - } - - /** - * Provides a customizable Read-Eval-Print-Loop (REPL). - * - * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those - * according to a user-defined evaluation function, then output the result. Input and output - * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. - * - * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style - * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session - * state, error recovery, and customizable evaluation functions. - * - * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ - * be created directly using the JavaScript `new` keyword. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl - */ - class REPLServer extends Interface { - /** - * The `vm.Context` provided to the `eval` function to be used for JavaScript - * evaluation. - */ - readonly context: Context; - /** - * The `Readable` stream from which REPL input will be read. - */ - readonly inputStream: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - */ - readonly outputStream: NodeJS.WritableStream; - /** - * The commands registered via `replServer.defineCommand()`. - */ - readonly commands: { readonly [name: string]: REPLCommand | undefined }; - /** - * A value indicating whether the REPL is currently in "editor mode". - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys - */ - readonly editorMode: boolean; - /** - * A value indicating whether the `_` variable has been assigned. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreAssigned: boolean; - /** - * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly last: any; - /** - * A value indicating whether the `_error` variable has been assigned. - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreErrAssigned: boolean; - /** - * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly lastError: any; - /** - * Specified in the REPL options, this is the function to be used when evaluating each - * given line of input. If not specified in the REPL options, this is an async wrapper - * for the JavaScript `eval()` function. - */ - readonly eval: REPLEval; - /** - * Specified in the REPL options, this is a value indicating whether the default - * `writer` function should include ANSI color styling to REPL output. - */ - readonly useColors: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `eval` - * function will use the JavaScript `global` as the context as opposed to creating a new - * separate context for the REPL instance. - */ - readonly useGlobal: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `writer` - * function should output the result of a command if it evaluates to `undefined`. - */ - readonly ignoreUndefined: boolean; - /** - * Specified in the REPL options, this is the function to invoke to format the output of - * each command before writing to `outputStream`. If not specified in the REPL options, - * this will be a wrapper for `util.inspect`. - */ - readonly writer: REPLWriter; - /** - * Specified in the REPL options, this is the function to use for custom Tab auto-completion. - */ - readonly completer: Completer | AsyncCompleter; - /** - * Specified in the REPL options, this is a flag that specifies whether the default `eval` - * function should execute all JavaScript commands in strict mode or default (sloppy) mode. - * Possible values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - - /** - * NOTE: According to the documentation: - * - * > Instances of `repl.REPLServer` are created using the `repl.start()` method and - * > _should not_ be created directly using the JavaScript `new` keyword. - * - * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver - */ - private constructor(); - - /** - * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked - * by typing a `.` followed by the `keyword`. - * - * @param keyword The command keyword (_without_ a leading `.` character). - * @param cmd The function to invoke when the command is processed. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd - */ - defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; - /** - * Readies the REPL instance for input from the user, printing the configured `prompt` to a - * new line in the `output` and resuming the `input` to accept new input. - * - * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. - */ - displayPrompt(preserveCursor?: boolean): void; - /** - * Clears any command that has been buffered but not yet executed. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @since v9.0.0 - */ - clearBufferedCommand(): void; - - /** - * events.EventEmitter - * 1. close - inherited from `readline.Interface` - * 2. line - inherited from `readline.Interface` - * 3. pause - inherited from `readline.Interface` - * 4. resume - inherited from `readline.Interface` - * 5. SIGCONT - inherited from `readline.Interface` - * 6. SIGINT - inherited from `readline.Interface` - * 7. SIGTSTP - inherited from `readline.Interface` - * 8. exit - * 9. reset - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (context: Context) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: Context): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (context: Context) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (context: Context) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (context: Context) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (context: Context) => void): this; - } - - /** - * A flag passed in the REPL options. Evaluates expressions in sloppy mode. - */ - export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol - - /** - * A flag passed in the REPL options. Evaluates expressions in strict mode. - * This is equivalent to prefacing every repl statement with `'use strict'`. - */ - export const REPL_MODE_STRICT: symbol; // TODO: unique symbol - - /** - * Creates and starts a `repl.REPLServer` instance. - * - * @param options The options for the `REPLServer`. If `options` is a string, then it specifies - * the input prompt. - */ - function start(options?: string | ReplOptions): REPLServer; - - /** - * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors - */ - class Recoverable extends SyntaxError { - err: Error; - - constructor(err: Error); - } -} - -declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - - class Interface extends events.EventEmitter { - readonly terminal: boolean; - - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(options: ReadLineOptions); - - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): this; - resume(): this; - close(): void; - write(data: string | Buffer, key?: Key): void; - - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - } - - type ReadLine = Interface; // type forwarded for backwards compatiblity - - type Completer = (line: string) => CompleterResult; - type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; - - type CompleterResult = [string[], string]; - - interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer | AsyncCompleter; - terminal?: boolean; - historySize?: number; - prompt?: string; - crlfDelay?: number; - removeHistoryDuplicates?: boolean; - } - - function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; - function createInterface(options: ReadLineOptions): Interface; - - function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; - function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; - function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - function clearLine(stream: NodeJS.WritableStream, dir: number): void; - function clearScreenDown(stream: NodeJS.WritableStream): void; -} - -declare module "vm" { - interface Context { - [key: string]: any; - } - interface BaseOptions { - /** - * Specifies the filename used in stack traces produced by this script. - * Default: `''`. - */ - filename?: string; - /** - * Specifies the line number offset that is displayed in stack traces produced by this script. - * Default: `0`. - */ - lineOffset?: number; - /** - * Specifies the column number offset that is displayed in stack traces produced by this script. - * Default: `0` - */ - columnOffset?: number; - } - interface ScriptOptions extends BaseOptions { - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - interface RunningScriptOptions extends BaseOptions { - displayErrors?: boolean; - timeout?: number; - } - interface CompileFunctionOptions extends BaseOptions { - /** - * Provides an optional data with V8's code cache data for the supplied source. - */ - cachedData?: Buffer; - /** - * Specifies whether to produce new cache data. - * Default: `false`, - */ - produceCachedData?: boolean; - /** - * The sandbox/context in which the said function should be compiled in. - */ - parsingContext?: Context; - - /** - * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling - */ - contextExtensions?: Object[]; - } - class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - function createContext(sandbox?: Context): Context; - function isContext(sandbox: Context): boolean; - function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; - function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; - function runInThisContext(code: string, options?: RunningScriptOptions | string): any; - function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; -} - -declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as net from "net"; - - interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - killed: boolean; - pid: number; - kill(signal?: string): void; - send(message: any, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - ref(): void; - - /** - * events.EventEmitter - * 1. close - * 2. disconnect - * 3. error - * 4. exit - * 5. message - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (code: number, signal: string) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; - addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", code: number, signal: string): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number | null, signal: string | null): boolean; - emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (code: number, signal: string) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; - on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (code: number, signal: string) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; - once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (code: number, signal: string) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; - prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; - prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - } - - interface MessageOptions { - keepOpen?: boolean; - } - - type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; - - interface SpawnOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; - argv0?: string; - stdio?: StdioOptions; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - windowsVerbatimArguments?: boolean; - windowsHide?: boolean; - } - - function spawn(command: string, options?: SpawnOptions): ChildProcess; - function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; - - interface ExecOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; - } - - interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - - interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string | null; // specify `null`. - } - - interface ExecException extends Error { - cmd?: string; - killed?: boolean; - code?: number; - signal?: string; - } - - // no `options` definitely means stdout/stderr are `string`. - function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function exec( - command: string, - options: ({ encoding?: string | null } & ExecOptions) | undefined | null, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace exec { - function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - interface ExecFileOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; - windowsVerbatimArguments?: boolean; - } - interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: 'buffer' | null; - } - interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { - encoding: string; - } - - function execFile(file: string): ChildProcess; - function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; - function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; - - // no `options` definitely means stdout/stderr are `string`. - function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithBufferEncoding, - callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, - ): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithStringEncoding, - callback: (error: Error | null, stdout: string, stderr: string) => void, - ): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function execFile( - file: string, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function execFile( - file: string, - options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, - callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, - ): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, - callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, - ): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace execFile { - function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__( - file: string, - args: string[] | undefined | null, - options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, - ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - interface ForkOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - stdio?: StdioOptions; - windowsVerbatimArguments?: boolean; - uid?: number; - gid?: number; - } - function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; - - interface SpawnSyncOptions { - argv0?: string; // Not specified in the docs - cwd?: string; - input?: string | Buffer | NodeJS.TypedArray | DataView; - stdio?: StdioOptions; - env?: NodeJS.ProcessEnv; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string | number; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - windowsVerbatimArguments?: boolean; - windowsHide?: boolean; - } - interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - function spawnSync(command: string): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; - - interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer | Uint8Array; - stdio?: StdioOptions; - env?: NodeJS.ProcessEnv; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string | number; - maxBuffer?: number; - encoding?: string; - windowsHide?: boolean; - } - interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - function execSync(command: string): Buffer; - function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - function execSync(command: string, options?: ExecSyncOptions): Buffer; - - interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer | NodeJS.TypedArray | DataView; - stdio?: StdioOptions; - env?: NodeJS.ProcessEnv; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string | number; - maxBuffer?: number; - encoding?: string; - windowsHide?: boolean; - shell?: boolean | string; - } - interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - function execFileSync(command: string): Buffer; - function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; -} - -declare module "url" { - import { ParsedUrlQuery } from 'querystring'; - - interface UrlObjectCommon { - auth?: string; - hash?: string; - host?: string; - hostname?: string; - href?: string; - path?: string; - pathname?: string; - protocol?: string; - search?: string; - slashes?: boolean; - } - - // Input to `url.format` - interface UrlObject extends UrlObjectCommon { - port?: string | number; - query?: string | null | { [key: string]: any }; - } - - // Output of `url.parse` - interface Url extends UrlObjectCommon { - port?: string; - query?: string | null | ParsedUrlQuery; - } - - interface UrlWithParsedQuery extends Url { - query: ParsedUrlQuery; - } - - interface UrlWithStringQuery extends Url { - query: string | null; - } - - function parse(urlStr: string): UrlWithStringQuery; - function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; - function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; - function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; - - function format(URL: URL, options?: URLFormatOptions): string; - function format(urlObject: UrlObject | string): string; - function resolve(from: string, to: string): string; - - function domainToASCII(domain: string): string; - function domainToUnicode(domain: string): string; - - /** - * This function ensures the correct decodings of percent-encoded characters as - * well as ensuring a cross-platform valid absolute path string. - * @param url The file URL string or URL object to convert to a path. - */ - function fileURLToPath(url: string | URL): string; - - /** - * This function ensures that path is resolved absolutely, and that the URL - * control characters are correctly encoded when converting into a File URL. - * @param url The path to convert to a File URL. - */ - function pathToFileURL(url: string): URL; - - interface URLFormatOptions { - auth?: boolean; - fragment?: boolean; - search?: boolean; - unicode?: boolean; - } - - class URL { - constructor(input: string, base?: string | URL); - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toString(): string; - toJSON(): string; - } - - class URLSearchParams implements Iterable<[string, string]> { - constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); - append(name: string, value: string): void; - delete(name: string): void; - entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string, searchParams: this) => void): void; - get(name: string): string | null; - getAll(name: string): string[]; - has(name: string): boolean; - keys(): IterableIterator; - set(name: string, value: string): void; - sort(): void; - toString(): string; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - } -} - -declare module "dns" { - // Supported getaddrinfo flags. - const ADDRCONFIG: number; - const V4MAPPED: number; - - interface LookupOptions { - family?: number; - hints?: number; - all?: boolean; - verbatim?: boolean; - } - - interface LookupOneOptions extends LookupOptions { - all?: false; - } - - interface LookupAllOptions extends LookupOptions { - all: true; - } - - interface LookupAddress { - address: string; - family: number; - } - - function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; - function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; - function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lookup { - function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; - function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; - function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; - } - - function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; - - namespace lookupService { - function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; - } - - interface ResolveOptions { - ttl: boolean; - } - - interface ResolveWithTtlOptions extends ResolveOptions { - ttl: true; - } - - interface RecordWithTtl { - address: string; - ttl: number; - } - - /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ - type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; - - interface AnyARecord extends RecordWithTtl { - type: "A"; - } - - interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; - } - - interface MxRecord { - priority: number; - exchange: string; - } - - interface AnyMxRecord extends MxRecord { - type: "MX"; - } - - interface NaptrRecord { - flags: string; - service: string; - regexp: string; - replacement: string; - order: number; - preference: number; - } - - interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; - } - - interface SoaRecord { - nsname: string; - hostmaster: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minttl: number; - } - - interface AnySoaRecord extends SoaRecord { - type: "SOA"; - } - - interface SrvRecord { - priority: number; - weight: number; - port: number; - name: string; - } - - interface AnySrvRecord extends SrvRecord { - type: "SRV"; - } - - interface AnyTxtRecord { - type: "TXT"; - entries: string[]; - } - - interface AnyNsRecord { - type: "NS"; - value: string; - } - - interface AnyPtrRecord { - type: "PTR"; - value: string; - } - - interface AnyCnameRecord { - type: "CNAME"; - value: string; - } - - type AnyRecord = AnyARecord | - AnyAaaaRecord | - AnyCnameRecord | - AnyMxRecord | - AnyNaptrRecord | - AnyNsRecord | - AnyPtrRecord | - AnySoaRecord | - AnySrvRecord | - AnyTxtRecord; - - function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; - function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; - function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; - function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; - function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; - function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; - function resolve( - hostname: string, - rrtype: string, - callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve { - function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; - function __promisify__(hostname: string, rrtype: "ANY"): Promise; - function __promisify__(hostname: string, rrtype: "MX"): Promise; - function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; - function __promisify__(hostname: string, rrtype: "SOA"): Promise; - function __promisify__(hostname: string, rrtype: "SRV"): Promise; - function __promisify__(hostname: string, rrtype: "TXT"): Promise; - function __promisify__(hostname: string, rrtype: string): Promise; - } - - function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; - function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve4 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; - function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve6 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - namespace resolveCname { - function __promisify__(hostname: string): Promise; - } - - function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; - namespace resolveMx { - function __promisify__(hostname: string): Promise; - } - - function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; - namespace resolveNaptr { - function __promisify__(hostname: string): Promise; - } - - function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - namespace resolveNs { - function __promisify__(hostname: string): Promise; - } - - function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - namespace resolvePtr { - function __promisify__(hostname: string): Promise; - } - - function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; - namespace resolveSoa { - function __promisify__(hostname: string): Promise; - } - - function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; - namespace resolveSrv { - function __promisify__(hostname: string): Promise; - } - - function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; - namespace resolveTxt { - function __promisify__(hostname: string): Promise; - } - - function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; - namespace resolveAny { - function __promisify__(hostname: string): Promise; - } - - function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; - function setServers(servers: string[]): void; - function getServers(): string[]; - - // Error codes - const NODATA: string; - const FORMERR: string; - const SERVFAIL: string; - const NOTFOUND: string; - const NOTIMP: string; - const REFUSED: string; - const BADQUERY: string; - const BADNAME: string; - const BADFAMILY: string; - const BADRESP: string; - const CONNREFUSED: string; - const TIMEOUT: string; - const EOF: string; - const FILE: string; - const NOMEM: string; - const DESTRUCTION: string; - const BADSTR: string; - const BADFLAGS: string; - const NONAME: string; - const BADHINTS: string; - const NOTINITIALIZED: string; - const LOADIPHLPAPI: string; - const ADDRGETNETWORKPARAMS: string; - const CANCELLED: string; - - class Resolver { - getServers: typeof getServers; - setServers: typeof setServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - cancel(): void; - } -} - -declare module "net" { - import * as stream from "stream"; - import * as events from "events"; - import * as dns from "dns"; - - type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface SocketConstructorOpts { - fd?: number; - allowHalfOpen?: boolean; - readable?: boolean; - writable?: boolean; - } - - interface TcpSocketConnectOpts { - port: number; - host?: string; - localAddress?: string; - localPort?: number; - hints?: number; - family?: number; - lookup?: LookupFunction; - } - - interface IpcSocketConnectOpts { - path: string; - } - - type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; - - class Socket extends stream.Duplex { - constructor(options?: SocketConstructorOpts); - - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(data: any, encoding?: string, callback?: Function): void; - - connect(options: SocketConnectOpts, connectionListener?: Function): this; - connect(port: number, host: string, connectionListener?: Function): this; - connect(port: number, connectionListener?: Function): this; - connect(path: string, connectionListener?: Function): this; - - setEncoding(encoding?: string): this; - pause(): this; - resume(): this; - setTimeout(timeout: number, callback?: Function): this; - setNoDelay(noDelay?: boolean): this; - setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): AddressInfo | string; - unref(): void; - ref(): void; - - readonly bufferSize: number; - readonly bytesRead: number; - readonly bytesWritten: number; - readonly connecting: boolean; - readonly destroyed: boolean; - readonly localAddress: string; - readonly localPort: number; - readonly remoteAddress?: string; - readonly remoteFamily?: string; - readonly remotePort?: number; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - readableAll?: boolean; - writableAll?: boolean; - } - - // https://github.com/nodejs/node/blob/master/lib/net.js - class Server extends events.EventEmitter { - constructor(connectionListener?: (socket: Socket) => void); - constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); - - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; - listen(port?: number, hostname?: string, listeningListener?: Function): this; - listen(port?: number, backlog?: number, listeningListener?: Function): this; - listen(port?: number, listeningListener?: Function): this; - listen(path: string, backlog?: number, listeningListener?: Function): this; - listen(path: string, listeningListener?: Function): this; - listen(options: ListenOptions, listeningListener?: Function): this; - listen(handle: any, backlog?: number, listeningListener?: Function): this; - listen(handle: any, listeningListener?: Function): this; - close(callback?: Function): this; - address(): AddressInfo | string; - getConnections(cb: (error: Error | null, count: number) => void): void; - ref(): this; - unref(): this; - maxConnections: number; - connections: number; - listening: boolean; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - } - - interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; - - function createServer(connectionListener?: (socket: Socket) => void): Server; - function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; - function connect(options: NetConnectOpts, connectionListener?: Function): Socket; - function connect(port: number, host?: string, connectionListener?: Function): Socket; - function connect(path: string, connectionListener?: Function): Socket; - function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; - function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - function createConnection(path: string, connectionListener?: Function): Socket; - function isIP(input: string): number; - function isIPv4(input: string): boolean; - function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import { AddressInfo } from "net"; - import * as dns from "dns"; - import * as events from "events"; - - interface RemoteInfo { - address: string; - family: string; - port: number; - } - - interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } - - type SocketType = "udp4" | "udp6"; - - interface SocketOptions { - type: SocketType; - reuseAddr?: boolean; - recvBufferSize?: number; - sendBufferSize?: number; - lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; - } - - function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - class Socket extends events.EventEmitter { - send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - bind(port?: number, address?: string, callback?: () => void): void; - bind(port?: number, callback?: () => void): void; - bind(callback?: () => void): void; - bind(options: BindOptions, callback?: Function): void; - close(callback?: () => void): void; - address(): AddressInfo | string; - setBroadcast(flag: boolean): void; - setTTL(ttl: number): void; - setMulticastTTL(ttl: number): void; - setMulticastInterface(multicastInterface: string): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): this; - unref(): this; - setRecvBufferSize(size: number): void; - setSendBufferSize(size: number): void; - getRecvBufferSize(): number; - getSendBufferSize(): number; - - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - } -} - -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - - /** - * Valid types for path values in "fs". - */ - type PathLike = string | Buffer | URL; - - type BinaryData = Buffer | DataView | NodeJS.TypedArray; - class Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atimeMs: number; - mtimeMs: number; - ctimeMs: number; - birthtimeMs: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - class Dirent { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - name: string; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - } - - class ReadStream extends stream.Readable { - close(): void; - bytesRead: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: string | number): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmodSync(fd: number, mode: string | number): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; - function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - namespace realpathSync { - function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlinkSync(path: PathLike): void; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdirSync(path: PathLike): void; - - export interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * @default false - */ - recursive?: boolean; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777. - */ - mode?: number; - } - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException, files: string[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, - callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write( - fd: number, - string: any, - position: number | undefined | null, - encoding: string | undefined | null, - callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, - ): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - */ - function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathLike | number, - options: { encoding?: string | null; flag?: string; } | string | undefined | null, - callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, - ): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; - - type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, - listener?: (event: string, filename: string) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, - listener?: (event: string, filename: string | Buffer) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function existsSync(path: PathLike): boolean; - - namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - - // File Copy Constants - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - const O_EXCL: number; - - /** - * Constant for fs.open(). Flag indicating that if path identifies a terminal device, - * opening the path shall not cause that terminal to become the controlling terminal for the process - * (if the process does not already have one). - */ - const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - const O_DIRECTORY: number; - - /** - * constant for fs.open(). - * Flag indicating reading accesses to the file system will no longer result in - * an update to the atime information associated with the file. - * This flag is available on Linux operating systems only. - */ - const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, - * which causes the copy operation to fail if dest already exists. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - - namespace promises { - interface FileHandle { - /** - * Gets the file descriptor for this file handle. - */ - readonly fd: number; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for appending. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - */ - chown(uid: number, gid: number): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - chmod(mode: string | number): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - */ - datasync(): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - */ - sync(): Promise; - - /** - * Asynchronously reads data from the file. - * The `FileHandle` must have been opened for reading. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - */ - stat(): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param len If not specified, defaults to `0`. - */ - truncate(len?: number): Promise; - - /** - * Asynchronously change file timestamps of the file. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - utimes(atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously writes `buffer` to the file. - * The `FileHandle` must have been opened for writing. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous close(2) - close a `FileHandle`. - */ - close(): Promise; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode?: number): Promise; - - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only - * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if - * `dest` already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not - * supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode?: string | number): Promise; - - /** - * Asynchronously reads data from the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If - * `null`, data will be read from the current position. - */ - function read( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len?: number): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param handle A `FileHandle`. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(handle: FileHandle, len?: number): Promise; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param handle A `FileHandle`. - */ - function fdatasync(handle: FileHandle): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param handle A `FileHandle`. - */ - function fsync(handle: FileHandle): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - * @param handle A `FileHandle`. - */ - function fstat(handle: FileHandle): Promise; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike): Promise; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike): Promise; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param handle A `FileHandle`. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(handle: FileHandle, mode: string | number): Promise; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param handle A `FileHandle`. - */ - function fchown(handle: FileHandle, uid: number, gid: number): Promise; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - } -} - -declare module "path" { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string; - /** - * The file extension (if any) such as '.html' - */ - ext?: string; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string; - } - - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths paths to join. - */ - function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} parameter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, - * until an absolute path is found. If after using all {from} paths still no absolute path is found, - * the current working directory is used as well. The resulting path is normalized, - * and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - function resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - */ - function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - const sep: '\\' | '/'; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - const delimiter: ';' | ':'; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - function format(pathObject: FormatInputPathObject): string; - - namespace posix { - function normalize(p: string): string; - function join(...paths: any[]): string; - function resolve(...pathSegments: any[]): string; - function isAbsolute(p: string): boolean; - function relative(from: string, to: string): string; - function dirname(p: string): string; - function basename(p: string, ext?: string): string; - function extname(p: string): string; - const sep: string; - const delimiter: string; - function parse(p: string): ParsedPath; - function format(pP: FormatInputPathObject): string; - } - - namespace win32 { - function normalize(p: string): string; - function join(...paths: any[]): string; - function resolve(...pathSegments: any[]): string; - function isAbsolute(p: string): boolean; - function relative(from: string, to: string): string; - function dirname(p: string): string; - function basename(p: string, ext?: string): string; - function extname(p: string): string; - const sep: string; - const delimiter: string; - function parse(p: string): ParsedPath; - function format(pP: FormatInputPathObject): string; - } -} - -declare module "string_decoder" { - interface NodeStringDecoder { - write(buffer: Buffer): string; - end(buffer?: Buffer): string; - } - const StringDecoder: { - new(encoding?: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import * as crypto from "crypto"; - import * as dns from "dns"; - import * as net from "net"; - import * as stream from "stream"; - - const CLIENT_RENEG_LIMIT: number; - const CLIENT_RENEG_WINDOW: number; - - interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - - interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: { [index: string]: string[] | undefined }; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - ext_key_usage: string[]; - serialNumber: string; - raw: Buffer; - } - - interface DetailedPeerCertificate extends PeerCertificate { - issuerCertificate: DetailedPeerCertificate; - } - - interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } - - class TLSSocket extends net.Socket { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext, - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean, - /** - * An optional net.Server instance. - */ - server?: net.Server, - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean, - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. Defaults to false. - */ - rejectUnauthorized?: boolean, - /** - * An array of strings or a Buffer naming possible NPN protocols. - * (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) When the server - * receives both NPN and ALPN extensions from the client, ALPN takes - * precedence over NPN and the server does not send an NPN extension - * to the client. - */ - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer, - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean - }); - - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - - /** - * String containing the selected ALPN protocol. - * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. - */ - alpnProtocol?: string; - - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param detailed - If true; the full chain with issuer property will be returned. - * @returns An object representing the peer's certificate. - */ - getPeerCertificate(detailed: true): DetailedPeerCertificate; - getPeerCertificate(detailed?: false): PeerCertificate; - getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. - * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. - * The value `null` will be returned for server sockets or disconnected client sockets. - * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. - * @returns negotiated SSL/TLS protocol version of the current connection - */ - getProtocol(): string | null; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): any; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): any; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - */ - renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; - - /** - * events.EventEmitter - * 1. OCSPResponse - * 2. secureConnect - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - } - - interface TlsOptions extends SecureContextOptions { - handshakeTimeout?: number; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - sessionTimeout?: number; - ticketKeys?: Buffer; - } - - interface ConnectionOptions extends SecureContextOptions { - host?: string; - port?: number; - path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket - rejectUnauthorized?: boolean; // Defaults to true - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - checkServerIdentity?: typeof checkServerIdentity; - servername?: string; // SNI TLS Extension - session?: Buffer; - minDHSize?: number; - secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() - lookup?: net.LookupFunction; - } - - class Server extends net.Server { - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; - emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - } - - interface SecurePair { - encrypted: any; - cleartext: any; - } - - interface SecureContextOptions { - pfx?: string | Buffer | Array; - key?: string | Buffer | Array; - passphrase?: string; - cert?: string | Buffer | Array; - ca?: string | Buffer | Array; - ciphers?: string; - honorCipherOrder?: boolean; - ecdhCurve?: string; - clientCertEngine?: string; - crl?: string | Buffer | Array; - dhparam?: string | Buffer; - secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options - secureProtocol?: string; // SSL Method, e.g. SSLv23_method - sessionIdContext?: string; - } - - interface SecureContext { - context: any; - } - - /* - * Verifies the certificate `cert` is issued to host `host`. - * @host The hostname to verify the certificate against - * @cert PeerCertificate representing the peer's certificate - * - * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. - */ - function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; - function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - function createSecureContext(details: SecureContextOptions): SecureContext; - function getCiphers(): string[]; - - const DEFAULT_ECDH_CURVE: string; -} - -declare module "crypto" { - import * as stream from "stream"; - - interface Certificate { - exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; - exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; - verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; - } - const Certificate: { - new(): Certificate; - (): Certificate; - }; - - /** @deprecated since v10.0.0 */ - const fips: boolean; - - interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } - interface Credentials { context?: any; } - function createCredentials(details: CredentialDetails): Credentials; - function createHash(algorithm: string, options?: stream.TransformOptions): Hash; - function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; - - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - - interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; - type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; - interface CipherCCMOptions extends stream.TransformOptions { - authTagLength: number; - } - interface CipherGCMOptions extends stream.TransformOptions { - authTagLength?: number; - } - /** @deprecated since v10.0.0 use createCipheriv() */ - function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; - /** @deprecated since v10.0.0 use createCipheriv() */ - function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; - /** @deprecated since v10.0.0 use createCipheriv() */ - function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; - - function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; - function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; - function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; - - interface Cipher extends NodeJS.ReadWriteStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; - update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; - // second arg ignored - update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): this; - // getAuthTag(): Buffer; - // setAAD(buffer: Buffer): this; // docs only say buffer - } - interface CipherCCM extends Cipher { - setAAD(buffer: Buffer, options: { plaintextLength: number }): this; - getAuthTag(): Buffer; - } - interface CipherGCM extends Cipher { - setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; - getAuthTag(): Buffer; - } - /** @deprecated since v10.0.0 use createCipheriv() */ - function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; - /** @deprecated since v10.0.0 use createCipheriv() */ - function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; - /** @deprecated since v10.0.0 use createCipheriv() */ - function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; - - function createDecipheriv( - algorithm: CipherCCMTypes, - key: string | Buffer | NodeJS.TypedArray | DataView, - iv: string | Buffer | NodeJS.TypedArray | DataView, - options: CipherCCMOptions, - ): DecipherCCM; - function createDecipheriv( - algorithm: CipherGCMTypes, - key: string | Buffer | NodeJS.TypedArray | DataView, - iv: string | Buffer | NodeJS.TypedArray | DataView, - options?: CipherGCMOptions, - ): DecipherGCM; - function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; - - interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; - // second arg is ignored - update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): this; - // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; - // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; - } - interface DecipherCCM extends Decipher { - setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; - setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; - } - interface DecipherGCM extends Decipher { - setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; - setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; - } - - function createSign(algorithm: string, options?: stream.WritableOptions): Signer; - interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; - sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; - } - function createVerify(algorith: string, options?: stream.WritableOptions): Verify; - interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; - verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; - // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format - // The signature field accepts a TypedArray type, but it is only available starting ES2017 - } - function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; - function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - interface DiffieHellman { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; - setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; - setPrivateKey(private_key: string, encoding: string): void; - verifyError: number; - } - function getDiffieHellman(group_name: string): DiffieHellman; - function pbkdf2( - password: string | Buffer | NodeJS.TypedArray | DataView, - salt: string | Buffer | NodeJS.TypedArray | DataView, - iterations: number, - keylen: number, - digest: string, - callback: (err: Error | null, derivedKey: Buffer) => any, - ): void; - function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; - - function randomBytes(size: number): Buffer; - function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - function pseudoRandomBytes(size: number): Buffer; - function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - - function randomFillSync(buffer: T, offset?: number, size?: number): T; - function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; - - interface ScryptOptions { - N?: number; - r?: number; - p?: number; - maxmem?: number; - } - function scrypt( - password: string | Buffer | NodeJS.TypedArray | DataView, - salt: string | Buffer | NodeJS.TypedArray | DataView, - keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scrypt( - password: string | Buffer | NodeJS.TypedArray | DataView, - salt: string | Buffer | NodeJS.TypedArray | DataView, - keylen: number, - options: ScryptOptions, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; - - interface RsaPublicKey { - key: string; - padding?: number; - } - interface RsaPrivateKey { - key: string; - passphrase?: string; - padding?: number; - } - function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; - function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; - function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; - function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; - function getCiphers(): string[]; - function getCurves(): string[]; - function getHashes(): string[]; - class ECDH { - static convertKey( - key: string | Buffer | NodeJS.TypedArray | DataView, - curve: string, - inputEncoding?: HexBase64Latin1Encoding, - outputEncoding?: "latin1" | "hex" | "base64", - format?: "uncompressed" | "compressed" | "hybrid", - ): Buffer | string; - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; - setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - function createECDH(curve_name: string): ECDH; - function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: string; - - export type KeyType = 'rsa' | 'dsa' | 'ec'; - export type KeyFormat = 'pem' | 'der'; - - interface BasePrivateKeyEncodingOptions { - format: T; - cipher: string; - passphrase: string; - } - - interface RSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * @default 0x10001 - */ - publicExponent?: number; - - publicKeyEncoding: { - type: 'pkcs1' | 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs1' | 'pkcs8'; - }; - } - - interface DSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Size of q in bits - */ - divisorLength: number; - - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface ECKeyPairOptions { - /** - * Name of the curve to use. - */ - namedCurve: string; - - publicKeyEncoding: { - type: 'pkcs1' | 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'sec1' | 'pkcs8'; - }; - } - - interface KeyPairSyncResult { - publicKey: T1; - privateKey: T2; - } - - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - - namespace generateKeyPair { - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - - function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - } -} - -declare module "stream" { - import * as events from "events"; - - class internal extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - namespace internal { - class Stream extends internal { } - - interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?(this: Readable, size: number): void; - destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; - } - - class Readable extends Stream implements NodeJS.ReadableStream { - readable: boolean; - readonly readableHighWaterMark: number; - readonly readableLength: number; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - unpipe(destination?: NodeJS.WritableStream): this; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): this; - push(chunk: any, encoding?: string): boolean; - _destroy(error: Error | null, callback: (error: Error | null) => void): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. readable - * 5. error - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: any) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "data", chunk: any): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: any) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: any) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: any) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: any) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: any) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; - writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; - destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; - final?(this: Writable, callback: (error?: Error | null) => void): void; - } - - class Writable extends Stream implements NodeJS.WritableStream { - writable: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; - setDefaultEncoding(encoding: string): this; - end(cb?: () => void): void; - end(chunk: any, cb?: () => void): void; - end(chunk: any, encoding?: string, cb?: () => void): void; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - read?(this: Duplex, size: number): void; - write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; - writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; - final?(this: Duplex, callback: (error?: Error | null) => void): void; - destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; - } - - // Note: Duplex extends both Readable and Writable. - class Duplex extends Readable implements Writable { - writable: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; - setDefaultEncoding(encoding: string): this; - end(cb?: () => void): void; - end(chunk: any, cb?: () => void): void; - end(chunk: any, encoding?: string, cb?: () => void): void; - cork(): void; - uncork(): void; - } - - type TransformCallback = (error?: Error, data?: any) => void; - - interface TransformOptions extends DuplexOptions { - read?(this: Transform, size: number): void; - write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; - writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; - final?(this: Transform, callback: (error?: Error | null) => void): void; - destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; - transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; - flush?(this: Transform, callback: TransformCallback): void; - } - - class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: TransformCallback): void; - _flush(callback: TransformCallback): void; - } - - class PassThrough extends Transform { } - - function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; - namespace finished { - function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise; - } - - function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; - function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: T, - callback?: (err: NodeJS.ErrnoException) => void, - ): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: T, - callback?: (err: NodeJS.ErrnoException) => void, - ): T; - function pipeline(streams: Array, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array void)>, - ): NodeJS.WritableStream; - namespace pipeline { - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: NodeJS.WritableStream, - ): Promise; - function __promisify__(streams: Array): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array, - ): Promise; - } - } - - export = internal; -} - -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function debug(string: string): void; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function error(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function puts(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function print(...param: any[]): void; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - const inspect: { - (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - (object: any, options: InspectOptions): string; - colors: { - [color: string]: [number, number] | undefined - } - styles: { - [style: string]: string | undefined - } - defaultOptions: InspectOptions; - custom: symbol; - }; - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - interface CustomPromisify extends Function { - __promisify__: TCustom; - } - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - namespace promisify { - const custom: symbol; - } - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - class TextEncoder { - readonly encoding: string; - constructor(); - encode(input?: string): Uint8Array; - } -} - -declare module "assert" { - function internal(value: any, message?: string | Error): void; - namespace internal { - class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - code: 'ERR_ASSERTION'; - - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFn?: Function - }); - } - - function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ - function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; - function ok(value: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use strictEqual() instead. */ - function equal(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ - function notEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ - function deepEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ - function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - function strictEqual(actual: any, expected: any, message?: string | Error): void; - function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; - function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - - function throws(block: Function, message?: string | Error): void; - function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; - function doesNotThrow(block: Function, message?: string | Error): void; - function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; - - function ifError(value: any): void; - - function rejects(block: Function | Promise, message?: string | Error): Promise; - function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; - function doesNotReject(block: Function | Promise, message?: string | Error): Promise; - function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; - - const strict: typeof internal; - } - - export = internal; -} - -declare module "tty" { - import * as net from "net"; - - function isatty(fd: number): boolean; - class ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - class WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } -} - -declare module "domain" { - import * as events from "events"; - - class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - members: any[]; - enter(): void; - exit(): void; - } - - function create(): Domain; -} - -declare module "constants" { - const E2BIG: number; - const EACCES: number; - const EADDRINUSE: number; - const EADDRNOTAVAIL: number; - const EAFNOSUPPORT: number; - const EAGAIN: number; - const EALREADY: number; - const EBADF: number; - const EBADMSG: number; - const EBUSY: number; - const ECANCELED: number; - const ECHILD: number; - const ECONNABORTED: number; - const ECONNREFUSED: number; - const ECONNRESET: number; - const EDEADLK: number; - const EDESTADDRREQ: number; - const EDOM: number; - const EEXIST: number; - const EFAULT: number; - const EFBIG: number; - const EHOSTUNREACH: number; - const EIDRM: number; - const EILSEQ: number; - const EINPROGRESS: number; - const EINTR: number; - const EINVAL: number; - const EIO: number; - const EISCONN: number; - const EISDIR: number; - const ELOOP: number; - const EMFILE: number; - const EMLINK: number; - const EMSGSIZE: number; - const ENAMETOOLONG: number; - const ENETDOWN: number; - const ENETRESET: number; - const ENETUNREACH: number; - const ENFILE: number; - const ENOBUFS: number; - const ENODATA: number; - const ENODEV: number; - const ENOENT: number; - const ENOEXEC: number; - const ENOLCK: number; - const ENOLINK: number; - const ENOMEM: number; - const ENOMSG: number; - const ENOPROTOOPT: number; - const ENOSPC: number; - const ENOSR: number; - const ENOSTR: number; - const ENOSYS: number; - const ENOTCONN: number; - const ENOTDIR: number; - const ENOTEMPTY: number; - const ENOTSOCK: number; - const ENOTSUP: number; - const ENOTTY: number; - const ENXIO: number; - const EOPNOTSUPP: number; - const EOVERFLOW: number; - const EPERM: number; - const EPIPE: number; - const EPROTO: number; - const EPROTONOSUPPORT: number; - const EPROTOTYPE: number; - const ERANGE: number; - const EROFS: number; - const ESPIPE: number; - const ESRCH: number; - const ETIME: number; - const ETIMEDOUT: number; - const ETXTBSY: number; - const EWOULDBLOCK: number; - const EXDEV: number; - const WSAEINTR: number; - const WSAEBADF: number; - const WSAEACCES: number; - const WSAEFAULT: number; - const WSAEINVAL: number; - const WSAEMFILE: number; - const WSAEWOULDBLOCK: number; - const WSAEINPROGRESS: number; - const WSAEALREADY: number; - const WSAENOTSOCK: number; - const WSAEDESTADDRREQ: number; - const WSAEMSGSIZE: number; - const WSAEPROTOTYPE: number; - const WSAENOPROTOOPT: number; - const WSAEPROTONOSUPPORT: number; - const WSAESOCKTNOSUPPORT: number; - const WSAEOPNOTSUPP: number; - const WSAEPFNOSUPPORT: number; - const WSAEAFNOSUPPORT: number; - const WSAEADDRINUSE: number; - const WSAEADDRNOTAVAIL: number; - const WSAENETDOWN: number; - const WSAENETUNREACH: number; - const WSAENETRESET: number; - const WSAECONNABORTED: number; - const WSAECONNRESET: number; - const WSAENOBUFS: number; - const WSAEISCONN: number; - const WSAENOTCONN: number; - const WSAESHUTDOWN: number; - const WSAETOOMANYREFS: number; - const WSAETIMEDOUT: number; - const WSAECONNREFUSED: number; - const WSAELOOP: number; - const WSAENAMETOOLONG: number; - const WSAEHOSTDOWN: number; - const WSAEHOSTUNREACH: number; - const WSAENOTEMPTY: number; - const WSAEPROCLIM: number; - const WSAEUSERS: number; - const WSAEDQUOT: number; - const WSAESTALE: number; - const WSAEREMOTE: number; - const WSASYSNOTREADY: number; - const WSAVERNOTSUPPORTED: number; - const WSANOTINITIALISED: number; - const WSAEDISCON: number; - const WSAENOMORE: number; - const WSAECANCELLED: number; - const WSAEINVALIDPROCTABLE: number; - const WSAEINVALIDPROVIDER: number; - const WSAEPROVIDERFAILEDINIT: number; - const WSASYSCALLFAILURE: number; - const WSASERVICE_NOT_FOUND: number; - const WSATYPE_NOT_FOUND: number; - const WSA_E_NO_MORE: number; - const WSA_E_CANCELLED: number; - const WSAEREFUSED: number; - const SIGHUP: number; - const SIGINT: number; - const SIGILL: number; - const SIGABRT: number; - const SIGFPE: number; - const SIGKILL: number; - const SIGSEGV: number; - const SIGTERM: number; - const SIGBREAK: number; - const SIGWINCH: number; - const SSL_OP_ALL: number; - const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - const SSL_OP_CIPHER_SERVER_PREFERENCE: number; - const SSL_OP_CISCO_ANYCONNECT: number; - const SSL_OP_COOKIE_EXCHANGE: number; - const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - const SSL_OP_EPHEMERAL_RSA: number; - const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - const SSL_OP_NO_COMPRESSION: number; - const SSL_OP_NO_QUERY_MTU: number; - const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - const SSL_OP_NO_SSLv2: number; - const SSL_OP_NO_SSLv3: number; - const SSL_OP_NO_TICKET: number; - const SSL_OP_NO_TLSv1: number; - const SSL_OP_NO_TLSv1_1: number; - const SSL_OP_NO_TLSv1_2: number; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - const SSL_OP_SINGLE_DH_USE: number; - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - const SSL_OP_TLS_D5_BUG: number; - const SSL_OP_TLS_ROLLBACK_BUG: number; - const ENGINE_METHOD_DSA: number; - const ENGINE_METHOD_DH: number; - const ENGINE_METHOD_RAND: number; - const ENGINE_METHOD_ECDH: number; - const ENGINE_METHOD_ECDSA: number; - const ENGINE_METHOD_CIPHERS: number; - const ENGINE_METHOD_DIGESTS: number; - const ENGINE_METHOD_STORE: number; - const ENGINE_METHOD_PKEY_METHS: number; - const ENGINE_METHOD_PKEY_ASN1_METHS: number; - const ENGINE_METHOD_ALL: number; - const ENGINE_METHOD_NONE: number; - const DH_CHECK_P_NOT_SAFE_PRIME: number; - const DH_CHECK_P_NOT_PRIME: number; - const DH_UNABLE_TO_CHECK_GENERATOR: number; - const DH_NOT_SUITABLE_GENERATOR: number; - const NPN_ENABLED: number; - const RSA_PKCS1_PADDING: number; - const RSA_SSLV23_PADDING: number; - const RSA_NO_PADDING: number; - const RSA_PKCS1_OAEP_PADDING: number; - const RSA_X931_PADDING: number; - const RSA_PKCS1_PSS_PADDING: number; - const POINT_CONVERSION_COMPRESSED: number; - const POINT_CONVERSION_UNCOMPRESSED: number; - const POINT_CONVERSION_HYBRID: number; - const O_RDONLY: number; - const O_WRONLY: number; - const O_RDWR: number; - const S_IFMT: number; - const S_IFREG: number; - const S_IFDIR: number; - const S_IFCHR: number; - const S_IFBLK: number; - const S_IFIFO: number; - const S_IFSOCK: number; - const S_IRWXU: number; - const S_IRUSR: number; - const S_IWUSR: number; - const S_IXUSR: number; - const S_IRWXG: number; - const S_IRGRP: number; - const S_IWGRP: number; - const S_IXGRP: number; - const S_IRWXO: number; - const S_IROTH: number; - const S_IWOTH: number; - const S_IXOTH: number; - const S_IFLNK: number; - const O_CREAT: number; - const O_EXCL: number; - const O_NOCTTY: number; - const O_DIRECTORY: number; - const O_NOATIME: number; - const O_NOFOLLOW: number; - const O_SYNC: number; - const O_DSYNC: number; - const O_SYMLINK: number; - const O_DIRECT: number; - const O_NONBLOCK: number; - const O_TRUNC: number; - const O_APPEND: number; - const F_OK: number; - const R_OK: number; - const W_OK: number; - const X_OK: number; - const COPYFILE_EXCL: number; - const COPYFILE_FICLONE: number; - const COPYFILE_FICLONE_FORCE: number; - const UV_UDP_REUSEADDR: number; - const SIGQUIT: number; - const SIGTRAP: number; - const SIGIOT: number; - const SIGBUS: number; - const SIGUSR1: number; - const SIGUSR2: number; - const SIGPIPE: number; - const SIGALRM: number; - const SIGCHLD: number; - const SIGSTKFLT: number; - const SIGCONT: number; - const SIGSTOP: number; - const SIGTSTP: number; - const SIGTTIN: number; - const SIGTTOU: number; - const SIGURG: number; - const SIGXCPU: number; - const SIGXFSZ: number; - const SIGVTALRM: number; - const SIGPROF: number; - const SIGIO: number; - const SIGPOLL: number; - const SIGPWR: number; - const SIGSYS: number; - const SIGUNUSED: number; - const defaultCoreCipherList: string; - const defaultCipherList: string; - const ENGINE_METHOD_RSA: number; - const ALPN_ENABLED: number; -} - -declare module "module" { - export = NodeJS.Module; -} - -declare module "process" { - export = process; -} - -declare module "v8" { - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - - // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ - type DoesZapCodeSpaceFlag = 0 | 1; - - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - } - - function getHeapStatistics(): HeapInfo; - function getHeapSpaceStatistics(): HeapSpaceInfo[]; - function setFlagsFromString(flags: string): void; -} - -declare module "timers" { - function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; - namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; - } - function clearTimeout(timeoutId: NodeJS.Timeout): void; - function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; - function clearInterval(intervalId: NodeJS.Timeout): void; - function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; - namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; - } - function clearImmediate(immediateId: NodeJS.Immediate): void; -} - -declare module "console" { - export = console; -} - -/** - * Async Hooks module: https://nodejs.org/api/async_hooks.html - */ -declare module "async_hooks" { - /** - * Returns the asyncId of the current execution context. - */ - function executionAsyncId(): number; - - /** - * Returns the ID of the resource responsible for calling the callback that is currently being executed. - */ - function triggerAsyncId(): number; - - interface HookCallbacks { - /** - * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy - */ - init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; - - /** - * When an asynchronous operation is initiated or completes a callback is called to notify the user. - * The before callback is called just before said callback is executed. - * @param asyncId the unique identifier assigned to the resource about to execute the callback. - */ - before?(asyncId: number): void; - - /** - * Called immediately after the callback specified in before is completed. - * @param asyncId the unique identifier assigned to the resource which has executed the callback. - */ - after?(asyncId: number): void; - - /** - * Called when a promise has resolve() called. This may not be in the same execution id - * as the promise itself. - * @param asyncId the unique id for the promise that was resolve()d. - */ - promiseResolve?(asyncId: number): void; - - /** - * Called after the resource corresponding to asyncId is destroyed - * @param asyncId a unique ID for the async resource - */ - destroy?(asyncId: number): void; - } - - interface AsyncHook { - /** - * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. - */ - enable(): this; - - /** - * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. - */ - disable(): this; - } - - /** - * Registers functions to be called for different lifetime events of each async operation. - * @param options the callbacks to register - * @return an AsyncHooks instance used for disabling and enabling hooks - */ - function createHook(options: HookCallbacks): AsyncHook; - - interface AsyncResourceOptions { - /** - * The ID of the execution context that created this async event. - * Default: `executionAsyncId()` - */ - triggerAsyncId?: number; - - /** - * Disables automatic `emitDestroy` when the object is garbage collected. - * This usually does not need to be set (even if `emitDestroy` is called - * manually), unless the resource's `asyncId` is retrieved and the - * sensitive API's `emitDestroy` is called with it. - * Default: `false` - */ - requireManualDestroy?: boolean; - } - - /** - * The class AsyncResource was designed to be extended by the embedder's async resources. - * Using this users can easily trigger the lifetime events of their own resources. - */ - class AsyncResource { - /** - * AsyncResource() is meant to be extended. Instantiating a - * new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * async_hook.executionAsyncId() is used. - * @param type The type of async event. - * @param triggerAsyncId The ID of the execution context that created - * this async event (default: `executionAsyncId()`), or an - * AsyncResourceOptions object (since 9.3) - */ - constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); - - /** - * Call AsyncHooks before callbacks. - * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. - */ - emitBefore(): void; - - /** - * Call AsyncHooks after callbacks. - * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. - */ - emitAfter(): void; - - /** - * Call the provided function with the provided arguments in the - * execution context of the async resource. This will establish the - * context, trigger the AsyncHooks before callbacks, call the function, - * trigger the AsyncHooks after callbacks, and then restore the original - * execution context. - * @param fn The function to call in the execution context of this - * async resource. - * @param thisArg The receiver to be used for the function call. - * @param args Optional arguments to pass to the function. - */ - runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; - - /** - * Call AsyncHooks destroy callbacks. - */ - emitDestroy(): void; - - /** - * @return the unique ID assigned to this AsyncResource instance. - */ - asyncId(): number; - - /** - * @return the trigger ID for this AsyncResource instance. - */ - triggerAsyncId(): number; - } -} - -declare module "http2" { - import * as events from "events"; - import * as fs from "fs"; - import * as net from "net"; - import * as stream from "stream"; - import * as tls from "tls"; - import * as url from "url"; - - import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; - export { OutgoingHttpHeaders } from "http"; - - export interface IncomingHttpStatusHeader { - ":status"?: number; - } - - export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { - ":path"?: string; - ":method"?: string; - ":authority"?: string; - ":scheme"?: string; - } - - // Http2Stream - - export interface StreamPriorityOptions { - exclusive?: boolean; - parent?: number; - weight?: number; - silent?: boolean; - } - - export interface StreamState { - localWindowSize?: number; - state?: number; - streamLocalClose?: number; - streamRemoteClose?: number; - sumDependencyWeight?: number; - weight?: number; - } - - export interface ServerStreamResponseOptions { - endStream?: boolean; - waitForTrailers?: boolean; - } - - export interface StatOptions { - offset: number; - length: number; - } - - export interface ServerStreamFileResponseOptions { - statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; - getTrailers?: (trailers: OutgoingHttpHeaders) => void; - offset?: number; - length?: number; - } - - export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { - onError?: (err: NodeJS.ErrnoException) => void; - } - - export interface Http2Stream extends stream.Duplex { - readonly aborted: boolean; - readonly closed: boolean; - readonly destroyed: boolean; - readonly pending: boolean; - readonly rstCode: number; - readonly sentHeaders: OutgoingHttpHeaders; - readonly sentInfoHeaders?: OutgoingHttpHeaders[]; - readonly sentTrailers?: OutgoingHttpHeaders; - readonly session: Http2Session; - readonly state: StreamState; - /** - * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, - * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. - */ - readonly endAfterHeaders: boolean; - close(code?: number, callback?: () => void): void; - priority(options: StreamPriorityOptions): void; - setTimeout(msecs: number, callback?: () => void): void; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: () => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: "streamClosed", listener: (code: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "wantTrailers", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted"): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "frameError", frameType: number, errorCode: number): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: "streamClosed", code: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "wantTrailers"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: () => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: "streamClosed", listener: (code: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "wantTrailers", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: () => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: "streamClosed", listener: (code: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "wantTrailers", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: () => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "streamClosed", listener: (code: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "wantTrailers", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: () => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "wantTrailers", listener: () => void): this; - - sendTrailers(headers: OutgoingHttpHeaders): this; - } - - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - } - - export interface ServerHttp2Stream extends Http2Stream { - additionalHeaders(headers: OutgoingHttpHeaders): void; - readonly headersSent: boolean; - readonly pushAllowed: boolean; - pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; - respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; - respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; - } - - // Http2Session - - export interface Settings { - headerTableSize?: number; - enablePush?: boolean; - initialWindowSize?: number; - maxFrameSize?: number; - maxConcurrentStreams?: number; - maxHeaderListSize?: number; - } - - export interface ClientSessionRequestOptions { - endStream?: boolean; - exclusive?: boolean; - parent?: number; - weight?: number; - getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; - } - - export interface SessionState { - effectiveLocalWindowSize?: number; - effectiveRecvDataLength?: number; - nextStreamID?: number; - localWindowSize?: number; - lastProcStreamID?: number; - remoteWindowSize?: number; - outboundQueueSize?: number; - deflateDynamicTableSize?: number; - inflateDynamicTableSize?: number; - } - - export interface Http2Session extends events.EventEmitter { - readonly alpnProtocol?: string; - close(callback?: () => void): void; - readonly closed: boolean; - readonly connecting: boolean; - destroy(error?: Error, code?: number): void; - readonly destroyed: boolean; - readonly encrypted?: boolean; - goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; - readonly localSettings: Settings; - readonly originSet?: string[]; - readonly pendingSettingsAck: boolean; - ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; - ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; - ref(): void; - readonly remoteSettings: Settings; - rstStream(stream: Http2Stream, code?: number): void; - setTimeout(msecs: number, callback?: () => void): void; - readonly socket: net.Socket | tls.TLSSocket; - readonly state: SessionState; - priority(stream: Http2Stream, options: StreamPriorityOptions): void; - settings(settings: Settings): void; - readonly type: number; - unref(): void; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - addListener(event: "localSettings", listener: (settings: Settings) => void): this; - addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "ping", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; - emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; - emit(event: "localSettings", settings: Settings): boolean; - emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "timeout"): boolean; - emit(event: "ping"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - on(event: "localSettings", listener: (settings: Settings) => void): this; - on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "ping", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - once(event: "localSettings", listener: (settings: Settings) => void): this; - once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "ping", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "ping", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "ping", listener: () => void): this; - } - - export interface ClientHttp2Session extends Http2Session { - request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; - emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - } - - export interface AlternativeServiceOptions { - origin: number | string | url.URL; - } - - export interface ServerHttp2Session extends Http2Session { - altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; - readonly server: Http2Server | Http2SecureServer; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - } - - // Http2Server - - export interface SessionOptions { - maxDeflateDynamicTableSize?: number; - maxReservedRemoteStreams?: number; - maxSendHeaderBlockLength?: number; - paddingStrategy?: number; - peerMaxConcurrentStreams?: number; - selectPadding?: (frameLen: number, maxFrameLen: number) => number; - settings?: Settings; - createConnection?: (option: SessionOptions) => stream.Duplex; - } - - export type ClientSessionOptions = SessionOptions; - export type ServerSessionOptions = SessionOptions; - - export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } - export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } - - export interface ServerOptions extends ServerSessionOptions { - allowHTTP1?: boolean; - } - - export interface SecureServerOptions extends SecureServerSessionOptions { - allowHTTP1?: boolean; - } - - export interface Http2Server extends net.Server { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export interface Http2SecureServer extends tls.Server { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - } - - export class Http2ServerRequest extends stream.Readable { - private constructor(); - headers: IncomingHttpHeaders; - httpVersion: string; - method: string; - rawHeaders: string[]; - rawTrailers: string[]; - setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; - stream: ServerHttp2Stream; - trailers: IncomingHttpHeaders; - url: string; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted", hadError: boolean, code: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - } - - export class Http2ServerResponse extends events.EventEmitter { - private constructor(); - addTrailers(trailers: OutgoingHttpHeaders): void; - connection: net.Socket | tls.TLSSocket; - end(callback?: () => void): void; - end(data?: string | Buffer, callback?: () => void): void; - end(data?: string | Buffer, encoding?: string, callback?: () => void): void; - readonly finished: boolean; - getHeader(name: string): string; - getHeaderNames(): string[]; - getHeaders(): OutgoingHttpHeaders; - hasHeader(name: string): boolean; - readonly headersSent: boolean; - removeHeader(name: string): void; - sendDate: boolean; - setHeader(name: string, value: number | string | string[]): void; - setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; - statusCode: number; - statusMessage: ''; - stream: ServerHttp2Stream; - write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; - write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; - writeContinue(): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; - createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted", hadError: boolean, code: number): boolean; - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "finish"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "finish", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "finish", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - } - - // Public API - - export namespace constants { - const NGHTTP2_SESSION_SERVER: number; - const NGHTTP2_SESSION_CLIENT: number; - const NGHTTP2_STREAM_STATE_IDLE: number; - const NGHTTP2_STREAM_STATE_OPEN: number; - const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - const NGHTTP2_STREAM_STATE_CLOSED: number; - const NGHTTP2_NO_ERROR: number; - const NGHTTP2_PROTOCOL_ERROR: number; - const NGHTTP2_INTERNAL_ERROR: number; - const NGHTTP2_FLOW_CONTROL_ERROR: number; - const NGHTTP2_SETTINGS_TIMEOUT: number; - const NGHTTP2_STREAM_CLOSED: number; - const NGHTTP2_FRAME_SIZE_ERROR: number; - const NGHTTP2_REFUSED_STREAM: number; - const NGHTTP2_CANCEL: number; - const NGHTTP2_COMPRESSION_ERROR: number; - const NGHTTP2_CONNECT_ERROR: number; - const NGHTTP2_ENHANCE_YOUR_CALM: number; - const NGHTTP2_INADEQUATE_SECURITY: number; - const NGHTTP2_HTTP_1_1_REQUIRED: number; - const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - const NGHTTP2_FLAG_NONE: number; - const NGHTTP2_FLAG_END_STREAM: number; - const NGHTTP2_FLAG_END_HEADERS: number; - const NGHTTP2_FLAG_ACK: number; - const NGHTTP2_FLAG_PADDED: number; - const NGHTTP2_FLAG_PRIORITY: number; - const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - const DEFAULT_SETTINGS_ENABLE_PUSH: number; - const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - const MAX_MAX_FRAME_SIZE: number; - const MIN_MAX_FRAME_SIZE: number; - const MAX_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_DEFAULT_WEIGHT: number; - const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - const NGHTTP2_SETTINGS_ENABLE_PUSH: number; - const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - const PADDING_STRATEGY_NONE: number; - const PADDING_STRATEGY_MAX: number; - const PADDING_STRATEGY_CALLBACK: number; - const HTTP2_HEADER_STATUS: string; - const HTTP2_HEADER_METHOD: string; - const HTTP2_HEADER_AUTHORITY: string; - const HTTP2_HEADER_SCHEME: string; - const HTTP2_HEADER_PATH: string; - const HTTP2_HEADER_ACCEPT_CHARSET: string; - const HTTP2_HEADER_ACCEPT_ENCODING: string; - const HTTP2_HEADER_ACCEPT_LANGUAGE: string; - const HTTP2_HEADER_ACCEPT_RANGES: string; - const HTTP2_HEADER_ACCEPT: string; - const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - const HTTP2_HEADER_AGE: string; - const HTTP2_HEADER_ALLOW: string; - const HTTP2_HEADER_AUTHORIZATION: string; - const HTTP2_HEADER_CACHE_CONTROL: string; - const HTTP2_HEADER_CONNECTION: string; - const HTTP2_HEADER_CONTENT_DISPOSITION: string; - const HTTP2_HEADER_CONTENT_ENCODING: string; - const HTTP2_HEADER_CONTENT_LANGUAGE: string; - const HTTP2_HEADER_CONTENT_LENGTH: string; - const HTTP2_HEADER_CONTENT_LOCATION: string; - const HTTP2_HEADER_CONTENT_MD5: string; - const HTTP2_HEADER_CONTENT_RANGE: string; - const HTTP2_HEADER_CONTENT_TYPE: string; - const HTTP2_HEADER_COOKIE: string; - const HTTP2_HEADER_DATE: string; - const HTTP2_HEADER_ETAG: string; - const HTTP2_HEADER_EXPECT: string; - const HTTP2_HEADER_EXPIRES: string; - const HTTP2_HEADER_FROM: string; - const HTTP2_HEADER_HOST: string; - const HTTP2_HEADER_IF_MATCH: string; - const HTTP2_HEADER_IF_MODIFIED_SINCE: string; - const HTTP2_HEADER_IF_NONE_MATCH: string; - const HTTP2_HEADER_IF_RANGE: string; - const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - const HTTP2_HEADER_LAST_MODIFIED: string; - const HTTP2_HEADER_LINK: string; - const HTTP2_HEADER_LOCATION: string; - const HTTP2_HEADER_MAX_FORWARDS: string; - const HTTP2_HEADER_PREFER: string; - const HTTP2_HEADER_PROXY_AUTHENTICATE: string; - const HTTP2_HEADER_PROXY_AUTHORIZATION: string; - const HTTP2_HEADER_RANGE: string; - const HTTP2_HEADER_REFERER: string; - const HTTP2_HEADER_REFRESH: string; - const HTTP2_HEADER_RETRY_AFTER: string; - const HTTP2_HEADER_SERVER: string; - const HTTP2_HEADER_SET_COOKIE: string; - const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - const HTTP2_HEADER_TRANSFER_ENCODING: string; - const HTTP2_HEADER_TE: string; - const HTTP2_HEADER_UPGRADE: string; - const HTTP2_HEADER_USER_AGENT: string; - const HTTP2_HEADER_VARY: string; - const HTTP2_HEADER_VIA: string; - const HTTP2_HEADER_WWW_AUTHENTICATE: string; - const HTTP2_HEADER_HTTP2_SETTINGS: string; - const HTTP2_HEADER_KEEP_ALIVE: string; - const HTTP2_HEADER_PROXY_CONNECTION: string; - const HTTP2_METHOD_ACL: string; - const HTTP2_METHOD_BASELINE_CONTROL: string; - const HTTP2_METHOD_BIND: string; - const HTTP2_METHOD_CHECKIN: string; - const HTTP2_METHOD_CHECKOUT: string; - const HTTP2_METHOD_CONNECT: string; - const HTTP2_METHOD_COPY: string; - const HTTP2_METHOD_DELETE: string; - const HTTP2_METHOD_GET: string; - const HTTP2_METHOD_HEAD: string; - const HTTP2_METHOD_LABEL: string; - const HTTP2_METHOD_LINK: string; - const HTTP2_METHOD_LOCK: string; - const HTTP2_METHOD_MERGE: string; - const HTTP2_METHOD_MKACTIVITY: string; - const HTTP2_METHOD_MKCALENDAR: string; - const HTTP2_METHOD_MKCOL: string; - const HTTP2_METHOD_MKREDIRECTREF: string; - const HTTP2_METHOD_MKWORKSPACE: string; - const HTTP2_METHOD_MOVE: string; - const HTTP2_METHOD_OPTIONS: string; - const HTTP2_METHOD_ORDERPATCH: string; - const HTTP2_METHOD_PATCH: string; - const HTTP2_METHOD_POST: string; - const HTTP2_METHOD_PRI: string; - const HTTP2_METHOD_PROPFIND: string; - const HTTP2_METHOD_PROPPATCH: string; - const HTTP2_METHOD_PUT: string; - const HTTP2_METHOD_REBIND: string; - const HTTP2_METHOD_REPORT: string; - const HTTP2_METHOD_SEARCH: string; - const HTTP2_METHOD_TRACE: string; - const HTTP2_METHOD_UNBIND: string; - const HTTP2_METHOD_UNCHECKOUT: string; - const HTTP2_METHOD_UNLINK: string; - const HTTP2_METHOD_UNLOCK: string; - const HTTP2_METHOD_UPDATE: string; - const HTTP2_METHOD_UPDATEREDIRECTREF: string; - const HTTP2_METHOD_VERSION_CONTROL: string; - const HTTP_STATUS_CONTINUE: number; - const HTTP_STATUS_SWITCHING_PROTOCOLS: number; - const HTTP_STATUS_PROCESSING: number; - const HTTP_STATUS_OK: number; - const HTTP_STATUS_CREATED: number; - const HTTP_STATUS_ACCEPTED: number; - const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - const HTTP_STATUS_NO_CONTENT: number; - const HTTP_STATUS_RESET_CONTENT: number; - const HTTP_STATUS_PARTIAL_CONTENT: number; - const HTTP_STATUS_MULTI_STATUS: number; - const HTTP_STATUS_ALREADY_REPORTED: number; - const HTTP_STATUS_IM_USED: number; - const HTTP_STATUS_MULTIPLE_CHOICES: number; - const HTTP_STATUS_MOVED_PERMANENTLY: number; - const HTTP_STATUS_FOUND: number; - const HTTP_STATUS_SEE_OTHER: number; - const HTTP_STATUS_NOT_MODIFIED: number; - const HTTP_STATUS_USE_PROXY: number; - const HTTP_STATUS_TEMPORARY_REDIRECT: number; - const HTTP_STATUS_PERMANENT_REDIRECT: number; - const HTTP_STATUS_BAD_REQUEST: number; - const HTTP_STATUS_UNAUTHORIZED: number; - const HTTP_STATUS_PAYMENT_REQUIRED: number; - const HTTP_STATUS_FORBIDDEN: number; - const HTTP_STATUS_NOT_FOUND: number; - const HTTP_STATUS_METHOD_NOT_ALLOWED: number; - const HTTP_STATUS_NOT_ACCEPTABLE: number; - const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - const HTTP_STATUS_REQUEST_TIMEOUT: number; - const HTTP_STATUS_CONFLICT: number; - const HTTP_STATUS_GONE: number; - const HTTP_STATUS_LENGTH_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_FAILED: number; - const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - const HTTP_STATUS_URI_TOO_LONG: number; - const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - const HTTP_STATUS_EXPECTATION_FAILED: number; - const HTTP_STATUS_TEAPOT: number; - const HTTP_STATUS_MISDIRECTED_REQUEST: number; - const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - const HTTP_STATUS_LOCKED: number; - const HTTP_STATUS_FAILED_DEPENDENCY: number; - const HTTP_STATUS_UNORDERED_COLLECTION: number; - const HTTP_STATUS_UPGRADE_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_REQUIRED: number; - const HTTP_STATUS_TOO_MANY_REQUESTS: number; - const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - const HTTP_STATUS_NOT_IMPLEMENTED: number; - const HTTP_STATUS_BAD_GATEWAY: number; - const HTTP_STATUS_SERVICE_UNAVAILABLE: number; - const HTTP_STATUS_GATEWAY_TIMEOUT: number; - const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - const HTTP_STATUS_INSUFFICIENT_STORAGE: number; - const HTTP_STATUS_LOOP_DETECTED: number; - const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - const HTTP_STATUS_NOT_EXTENDED: number; - const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - } - - export function getDefaultSettings(): Settings; - export function getPackedSettings(settings: Settings): Settings; - export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; - - export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - - export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - - export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; - export function connect( - authority: string | url.URL, - options?: ClientSessionOptions | SecureClientSessionOptions, - listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): ClientHttp2Session; -} - -declare module "perf_hooks" { - import { AsyncResource } from "async_hooks"; - - interface PerformanceEntry { - /** - * The total number of milliseconds elapsed for this entry. - * This value will not be meaningful for all Performance Entry types. - */ - readonly duration: number; - - /** - * The name of the performance entry. - */ - readonly name: string; - - /** - * The high resolution millisecond timestamp marking the starting time of the Performance Entry. - */ - readonly startTime: number; - - /** - * The type of the performance entry. - * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. - */ - readonly entryType: string; - - /** - * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies - * the type of garbage collection operation that occurred. - * The value may be one of perf_hooks.constants. - */ - readonly kind?: number; - } - - interface PerformanceNodeTiming extends PerformanceEntry { - /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. - */ - readonly bootstrapComplete: number; - - /** - * The high resolution millisecond timestamp at which cluster processing ended. - */ - readonly clusterSetupEnd: number; - - /** - * The high resolution millisecond timestamp at which cluster processing started. - */ - readonly clusterSetupStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop exited. - */ - readonly loopExit: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop started. - */ - readonly loopStart: number; - - /** - * The high resolution millisecond timestamp at which main module load ended. - */ - readonly moduleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which main module load started. - */ - readonly moduleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js process was initialized. - */ - readonly nodeStart: number; - - /** - * The high resolution millisecond timestamp at which preload module load ended. - */ - readonly preloadModuleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which preload module load started. - */ - readonly preloadModuleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing ended. - */ - readonly thirdPartyMainEnd: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing started. - */ - readonly thirdPartyMainStart: number; - - /** - * The high resolution millisecond timestamp at which the V8 platform was initialized. - */ - readonly v8Start: number; - } - - interface Performance { - /** - * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. - * If name is provided, removes entries with name. - * @param name - */ - clearFunctions(name?: string): void; - - /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name - */ - clearMarks(name?: string): void; - - /** - * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. - * If name is provided, removes only objects whose performanceEntry.name matches name. - */ - clearMeasures(name?: string): void; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - * @return list of all PerformanceEntry objects - */ - getEntries(): PerformanceEntry[]; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - * @param name - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByType(type: string): PerformanceEntry[]; - - /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - */ - mark(name?: string): void; - - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - */ - measure(name: string, startMark: string, endMark: string): void; - - /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. - */ - readonly nodeTiming: PerformanceNodeTiming; - - /** - * @return the current high resolution millisecond timestamp - */ - now(): number; - - /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. - */ - readonly timeOrigin: number; - - /** - * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. - * @param fn - */ - timerify any>(fn: T): T; - } - - interface PerformanceObserverEntryList { - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - */ - getEntries(): PerformanceEntry[]; - - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; - - /** - * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - */ - getEntriesByType(type: string): PerformanceEntry[]; - } - - type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; - - class PerformanceObserver extends AsyncResource { - constructor(callback: PerformanceObserverCallback); - - /** - * Disconnects the PerformanceObserver instance from all notifications. - */ - disconnect(): void; - - /** - * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. - * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. - * Property buffered defaults to false. - * @param options - */ - observe(options: { entryTypes: string[], buffered?: boolean }): void; - } - - namespace constants { - const NODE_PERFORMANCE_GC_MAJOR: number; - const NODE_PERFORMANCE_GC_MINOR: number; - const NODE_PERFORMANCE_GC_INCREMENTAL: number; - const NODE_PERFORMANCE_GC_WEAKCB: number; - } - - const performance: Performance; -} - -declare module "trace_events" { - /** - * The `Tracing` object is used to enable or disable tracing for sets of - * categories. Instances are created using the - * `trace_events.createTracing()` method. - * - * When created, the `Tracing` object is disabled. Calling the - * `tracing.enable()` method adds the categories to the set of enabled trace - * event categories. Calling `tracing.disable()` will remove the categories - * from the set of enabled trace event categories. - */ - export interface Tracing { - /** - * A comma-separated list of the trace event categories covered by this - * `Tracing` object. - */ - readonly categories: string; - - /** - * Disables this `Tracing` object. - * - * Only trace event categories _not_ covered by other enabled `Tracing` - * objects and _not_ specified by the `--trace-event-categories` flag - * will be disabled. - */ - disable(): void; - - /** - * Enables this `Tracing` object for the set of categories covered by - * the `Tracing` object. - */ - enable(): void; - - /** - * `true` only if the `Tracing` object has been enabled. - */ - readonly enabled: boolean; - } - - interface CreateTracingOptions { - /** - * An array of trace category names. Values included in the array are - * coerced to a string when possible. An error will be thrown if the - * value cannot be coerced. - */ - categories: string[]; - } - - /** - * Creates and returns a Tracing object for the given set of categories. - */ - export function createTracing(options: CreateTracingOptions): Tracing; - - /** - * Returns a comma-separated list of all currently-enabled trace event - * categories. The current set of enabled trace event categories is - * determined by the union of all currently-enabled `Tracing` objects and - * any categories enabled using the `--trace-event-categories` flag. - */ - export function getEnabledCategories(): string; -} +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts index a9d0f1140a..2dcd2760ad 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -8,7 +8,6 @@ /** * The inspector module provides an API for interacting with the V8 inspector. */ -// tslint:disable-next-line:no-single-declare-module declare module "inspector" { import { EventEmitter } from 'events'; diff --git a/types/node/module.d.ts b/types/node/module.d.ts new file mode 100644 index 0000000000..f512be7e5e --- /dev/null +++ b/types/node/module.d.ts @@ -0,0 +1,3 @@ +declare module "module" { + export = NodeJS.Module; +} diff --git a/types/node/net.d.ts b/types/node/net.d.ts new file mode 100644 index 0000000000..27804375aa --- /dev/null +++ b/types/node/net.d.ts @@ -0,0 +1,251 @@ +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + write(data: any, encoding?: string, callback?: Function): void; + + connect(options: SocketConnectOpts, connectionListener?: Function): this; + connect(port: number, host: string, connectionListener?: Function): this; + connect(port: number, connectionListener?: Function): this; + connect(path: string, connectionListener?: Function): this; + + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port?: number, hostname?: string, listeningListener?: Function): this; + listen(port?: number, backlog?: number, listeningListener?: Function): this; + listen(port?: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + close(callback?: Function): this; + address(): AddressInfo | string; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: Function): Socket; + function connect(port: number, host?: string, connectionListener?: Function): Socket; + function connect(path: string, connectionListener?: Function): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; + function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + function createConnection(path: string, connectionListener?: Function): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} diff --git a/types/node/os.d.ts b/types/node/os.d.ts new file mode 100644 index 0000000000..c85d217f91 --- /dev/null +++ b/types/node/os.d.ts @@ -0,0 +1,192 @@ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + function homedir(): string; + function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; + const constants: { + UV_UDP_REUSEADDR: number; + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + function arch(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} diff --git a/types/node/path.d.ts b/types/node/path.d.ts new file mode 100644 index 0000000000..bbc17098f4 --- /dev/null +++ b/types/node/path.d.ts @@ -0,0 +1,159 @@ +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + + namespace posix { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } + + namespace win32 { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } +} diff --git a/types/node/perf_hooks.d.ts b/types/node/perf_hooks.d.ts new file mode 100644 index 0000000000..4f68895ce6 --- /dev/null +++ b/types/node/perf_hooks.d.ts @@ -0,0 +1,241 @@ +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} diff --git a/types/node/process.d.ts b/types/node/process.d.ts new file mode 100644 index 0000000000..ccd5c9c198 --- /dev/null +++ b/types/node/process.d.ts @@ -0,0 +1,3 @@ +declare module "process" { + export = process; +} diff --git a/types/node/punycode.d.ts b/types/node/punycode.d.ts new file mode 100644 index 0000000000..efc55622f1 --- /dev/null +++ b/types/node/punycode.d.ts @@ -0,0 +1,12 @@ +declare module "punycode" { + function decode(string: string): string; + function encode(string: string): string; + function toUnicode(domain: string): string; + function toASCII(domain: string): string; + const ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + const version: any; +} diff --git a/types/node/querystring.d.ts b/types/node/querystring.d.ts new file mode 100644 index 0000000000..f54d352c6c --- /dev/null +++ b/types/node/querystring.d.ts @@ -0,0 +1,17 @@ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: Function; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + interface ParsedUrlQuery { [key: string]: string | string[]; } + + function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + function escape(str: string): string; + function unescape(str: string): string; +} diff --git a/types/node/readline.d.ts b/types/node/readline.d.ts new file mode 100644 index 0000000000..9c25da4982 --- /dev/null +++ b/types/node/readline.d.ts @@ -0,0 +1,135 @@ +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + type ReadLine = Interface; // type forwarded for backwards compatiblity + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; +} diff --git a/types/node/repl.d.ts b/types/node/repl.d.ts new file mode 100644 index 0000000000..cb5a3d037b --- /dev/null +++ b/types/node/repl.d.ts @@ -0,0 +1,372 @@ +declare module "repl" { + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; + + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} diff --git a/types/node/scripts/generate-inspector/inspector.d.ts.template b/types/node/scripts/generate-inspector/inspector.d.ts.template index 11b8f33403..a6715f12e4 100644 --- a/types/node/scripts/generate-inspector/inspector.d.ts.template +++ b/types/node/scripts/generate-inspector/inspector.d.ts.template @@ -8,7 +8,6 @@ /** * The inspector module provides an API for interacting with the V8 inspector. */ -// tslint:disable-next-line:no-single-declare-module declare module "inspector" { import { EventEmitter } from 'events'; diff --git a/types/node/stream.d.ts b/types/node/stream.d.ts new file mode 100644 index 0000000000..a4428728db --- /dev/null +++ b/types/node/stream.d.ts @@ -0,0 +1,294 @@ +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { } + + interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise; + } + + function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline(streams: Array, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise; + function __promisify__(streams: Array): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; + } + } + + export = internal; +} diff --git a/types/node/string_decoder.d.ts b/types/node/string_decoder.d.ts new file mode 100644 index 0000000000..762a4d8d50 --- /dev/null +++ b/types/node/string_decoder.d.ts @@ -0,0 +1,9 @@ +declare module "string_decoder" { + interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + const StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} diff --git a/types/node/timers.d.ts b/types/node/timers.d.ts new file mode 100644 index 0000000000..e64a6735c3 --- /dev/null +++ b/types/node/timers.d.ts @@ -0,0 +1,16 @@ +declare module "timers" { + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} diff --git a/types/node/tls.d.ts b/types/node/tls.d.ts new file mode 100644 index 0000000000..f59dcc7629 --- /dev/null +++ b/types/node/tls.d.ts @@ -0,0 +1,371 @@ +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + } + + class Server extends net.Server { + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + interface SecurePair { + encrypted: any; + cleartext: any; + } + + interface SecureContextOptions { + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; + passphrase?: string; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(details: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + const DEFAULT_ECDH_CURVE: string; +} diff --git a/types/node/trace_events.d.ts b/types/node/trace_events.d.ts new file mode 100644 index 0000000000..9d1a59bdd0 --- /dev/null +++ b/types/node/trace_events.d.ts @@ -0,0 +1,61 @@ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 5c06ec7625..9675935b6a 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -1,7 +1,46 @@ { "files": [ "index.d.ts", + "globals.d.ts", + "assert.d.ts", + "async_hooks.d.ts", + "buffer.d.ts", + "child_process.d.ts", + "cluster.d.ts", + "console.d.ts", + "constants.d.ts", + "crypto.d.ts", + "dgram.d.ts", + "dns.d.ts", + "domain.d.ts", + "events.d.ts", + "fs.d.ts", + "http.d.ts", + "http2.d.ts", + "https.d.ts", "inspector.d.ts", + "module.d.ts", + "net.d.ts", + "os.d.ts", + "path.d.ts", + "perf_hooks.d.ts", + "process.d.ts", + "punycode.d.ts", + "querystring.d.ts", + "readline.d.ts", + "repl.d.ts", + "stream.d.ts", + "string_decoder.d.ts", + "timers.d.ts", + "tls.d.ts", + "trace_events.d.ts", + "tty.d.ts", + "url.d.ts", + "util.d.ts", + "v8.d.ts", + "vm.d.ts", + "worker_threads.d.ts", + "zlib.d.ts", "node-tests.ts" ], "compilerOptions": { diff --git a/types/node/tslint.json b/types/node/tslint.json index 5f35deba40..1a8ddd9863 100644 --- a/types/node/tslint.json +++ b/types/node/tslint.json @@ -4,6 +4,7 @@ "ban-types": false, "unified-signatures": false, "no-empty-interface": false, + "no-single-declare-module": false, "strict-export-declare-modifiers": false // http2 needs this } } diff --git a/types/node/tty.d.ts b/types/node/tty.d.ts new file mode 100644 index 0000000000..7d75c89f58 --- /dev/null +++ b/types/node/tty.d.ts @@ -0,0 +1,15 @@ +declare module "tty" { + import * as net from "net"; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + class WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} diff --git a/types/node/url.d.ts b/types/node/url.d.ts new file mode 100644 index 0000000000..1e1d154e8e --- /dev/null +++ b/types/node/url.d.ts @@ -0,0 +1,104 @@ +declare module "url" { + import { ParsedUrlQuery } from 'querystring'; + + interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + function parse(urlStr: string): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} diff --git a/types/node/util.d.ts b/types/node/util.d.ts new file mode 100644 index 0000000000..f918286559 --- /dev/null +++ b/types/node/util.d.ts @@ -0,0 +1,173 @@ +declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + const inspect: { + (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + (object: any, options: InspectOptions): string; + colors: { + [color: string]: [number, number] | undefined + } + styles: { + [style: string]: string | undefined + } + defaultOptions: InspectOptions; + custom: symbol; + }; + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace promisify { + const custom: symbol; + } + + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isAsyncFunction(object: any): boolean; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + constructor(); + encode(input?: string): Uint8Array; + } +} diff --git a/types/node/v8.d.ts b/types/node/v8.d.ts new file mode 100644 index 0000000000..ee5f707234 --- /dev/null +++ b/types/node/v8.d.ts @@ -0,0 +1,28 @@ +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; +} diff --git a/types/node/vm.d.ts b/types/node/vm.d.ts new file mode 100644 index 0000000000..404fa9c820 --- /dev/null +++ b/types/node/vm.d.ts @@ -0,0 +1,64 @@ +declare module "vm" { + interface Context { + [key: string]: any; + } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + function createContext(sandbox?: Context): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; +} diff --git a/types/node/worker_threads.d.ts b/types/node/worker_threads.d.ts new file mode 100644 index 0000000000..b20748a34f --- /dev/null +++ b/types/node/worker_threads.d.ts @@ -0,0 +1,124 @@ +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} diff --git a/types/node/zlib.d.ts b/types/node/zlib.d.ts new file mode 100644 index 0000000000..d362d481b6 --- /dev/null +++ b/types/node/zlib.d.ts @@ -0,0 +1,138 @@ +declare module "zlib" { + import * as stream from "stream"; + + interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + } + + interface Zlib { + readonly bytesRead: number; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + // Allowed flush values. + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + // Compression levels. + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + // Constants + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + const Z_BINARY: number; + const Z_TEXT: number; + const Z_ASCII: number; + const Z_UNKNOWN: number; + const Z_DEFLATED: number; +} From 140d0dc3e477b99a4bd1e1b6452560bfd702f35f Mon Sep 17 00:00:00 2001 From: Andrew MacLeay Date: Mon, 28 Jan 2019 15:24:13 -0500 Subject: [PATCH 133/312] @storybook/addon-notes: support global decorator Support the global decorator usage supplied in [the README](https://github.com/storybooks/storybook/blob/9f30442098e5350f5ba4872887cf9d1a03146e74/addons/ondevice-notes/README.md#getting-started) --- types/storybook__addon-notes/index.d.ts | 4 ++++ .../storybook__addon-notes/storybook__addon-notes-tests.tsx | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/types/storybook__addon-notes/index.d.ts b/types/storybook__addon-notes/index.d.ts index b669ce0a9c..096da8fa34 100644 --- a/types/storybook__addon-notes/index.d.ts +++ b/types/storybook__addon-notes/index.d.ts @@ -17,5 +17,9 @@ export type WithNotesOptions = string | { markdownOptions?: MarkedOptions; }; +// It would be preferable to infer the argument types, but that requires TS v 3.1 +// export function withNotes(...args: StoryDecorator extends (...a: infer A) => any ? A : never): ReturnType; +export function withNotes(story: RenderFunction, context: { kind: string, story: string }): ReturnType; +// Less-preferred but still supported: export function withNotes(options?: WithNotesOptions): StoryDecorator; export function withMarkdownNotes(markdown: string, options?: MarkedOptions): StoryDecorator; diff --git a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx b/types/storybook__addon-notes/storybook__addon-notes-tests.tsx index ebf24ce227..edfe0daf14 100644 --- a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx +++ b/types/storybook__addon-notes/storybook__addon-notes-tests.tsx @@ -1,8 +1,11 @@ import * as React from 'react'; -import { storiesOf } from '@storybook/react'; +import { addDecorator, storiesOf } from '@storybook/react'; import { withNotes, withMarkdownNotes, } from '@storybook/addon-notes'; +// New, preferred global registration: +addDecorator(withNotes); + const SIMPLE_MARKDOWN = ` ## Markdown for component From f42e2acfbfeda3ed3d183ad00e6b958a5bfe0574 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 28 Jan 2019 12:54:16 -0800 Subject: [PATCH 134/312] Fix jsforce definitions --- types/jsforce/api/chatter.d.ts | 6 +----- types/jsforce/api/metadata.d.ts | 6 +----- types/jsforce/jsforce-tests.ts | 6 +++--- types/jsforce/tslint.json | 1 + 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index c712187559..4b65740f36 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -27,7 +27,7 @@ interface RequestParams { export class RequestResult { } -export class Request implements Promise { +export class Request implements PromiseLike { constructor(chatter: Chatter, params: RequestParams); batchParams(): BatchRequestParams; @@ -36,16 +36,12 @@ export class Request implements Promise { stream(): Stream; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; thenCall(callback?: (err: Error, records: T) => void): Query; - - readonly [Symbol.toStringTag]: 'Promise'; } export class Resource extends Request { diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index c6aec12e7e..88dbdaa52d 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -112,21 +112,17 @@ interface DeployOptions { singlePackage?: boolean; } -export class AsyncResultLocator extends EventEmitter implements Promise { +export class AsyncResultLocator extends EventEmitter implements PromiseLike { check(callback?: Callback): Promise complete(callback?: Callback): Promise poll(interval: number, timeout: number): void; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; - - readonly [Symbol.toStringTag]: "Promise"; } export class DeployResultLocator extends AsyncResultLocator {} diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index 08ea888062..45442b91dc 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -615,7 +615,7 @@ async function testChatter(conn: sf.Connection): Promise { const feedResource: sf.Resource = chatter.resource('/feed-elements'); - const feedCreateRequest: any = await (feedResource.create({ + const feedCreateRequest: any = await feedResource.create({ body: { messageSegments: [{ type: 'Text', @@ -624,13 +624,13 @@ async function testChatter(conn: sf.Connection): Promise { }, feedElementType: 'FeedItem', subjectId: 'me' - }) as Promise); + }); console.log(`feedCreateRequest.id: ${feedCreateRequest.id}`); const itemLikesUrl = `/feed-elements/${feedCreateRequest.id}/capabilities/chatter-likes/items`; const itemsLikeResource: sf.Resource = chatter.resource(itemLikesUrl); - const itemsLikeCreateResult: sf.RequestResult = await (itemsLikeResource.create('') as Promise); + const itemsLikeCreateResult: sf.RequestResult = await itemsLikeResource.create(''); console.log(`itemsLikeCreateResult['likedItem']: ${itemsLikeCreateResult as any['likedItem']}`); } diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index 43829466b8..12201695b9 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODOs "array-type": false, + "await-promise": [true, "Request"], "ban-types": false, "eofline": false, "max-line-length": false, From d9673b8dffa261050a88a47450cb91d217d84e15 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 28 Jan 2019 13:24:20 -0800 Subject: [PATCH 135/312] Fix dependency for chai-webdriverio --- types/chai-webdriverio/package.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 types/chai-webdriverio/package.json diff --git a/types/chai-webdriverio/package.json b/types/chai-webdriverio/package.json new file mode 100644 index 0000000000..cd495fe983 --- /dev/null +++ b/types/chai-webdriverio/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/webdriverio": "^4.0.0" + } +} From 17e7655380cfea842802eacc8e999331b9e9f814 Mon Sep 17 00:00:00 2001 From: Matthieu Vachon Date: Mon, 21 Jan 2019 15:29:51 -0500 Subject: [PATCH 136/312] Added possibility to pass array to SpaceProps Remove all disabled rules in `tslint.json`. It means all rules are now active. --- types/rebass/index.d.ts | 62 +++++++++++++--------------- types/rebass/rebass-tests.tsx | 10 ++--- types/rebass/tslint.json | 78 +---------------------------------- 3 files changed, 34 insertions(+), 116 deletions(-) diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index f05d136f69..0536a600ee 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Rebass 0.3.8 +// Type definitions for Rebass 3.0 // Project: https://github.com/jxnblk/rebass -// Definitions by: rhysd +// Definitions by: rhysd // ryee-dev // jamesmckenzie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,32 +14,33 @@ export interface BaseProps extends React.ClassAttributes { } export interface SpaceProps extends BaseProps { - m?: number | string; - mt?: number | string; - mr?: number | string; - mb?: number | string; - ml?: number | string; - mx?: number | string; - my?: number | string; - p?: number | string; - pt?: number | string; - pr?: number | string; - pb?: number | string; - pl?: number | string; - px?: number | string; - py?: number | string; + m?: number | string | ReadonlyArray; + mt?: number | string | ReadonlyArray; + mr?: number | string | ReadonlyArray; + mb?: number | string | ReadonlyArray; + ml?: number | string | ReadonlyArray; + mx?: number | string | ReadonlyArray; + my?: number | string | ReadonlyArray; + p?: number | string | ReadonlyArray; + pt?: number | string | ReadonlyArray; + pr?: number | string | ReadonlyArray; + pb?: number | string | ReadonlyArray; + pl?: number | string | ReadonlyArray; + px?: number | string | ReadonlyArray; + py?: number | string | ReadonlyArray; } export interface BoxProps extends SpaceProps { className?: string; width?: number | string | ReadonlyArray; fontSize?: number | ReadonlyArray; - css?: Object; + css?: object; color?: string; bg?: string; } -type BoxClass = React.StatelessComponent; -export declare const Box: BoxClass; +// tslint:disable-next-line:strict-export-declare-modifiers +type BoxClass = React.FunctionComponent; +export const Box: BoxClass; export interface ButtonProps extends BoxProps { fontWeight?: string; @@ -48,8 +49,7 @@ export interface ButtonProps extends BoxProps { borderRadius?: number | string; variant?: string; } -type ButtonClass = React.StatelessComponent; -export declare const Button: ButtonClass; +export const Button: React.FunctionComponent; export interface CardProps extends BoxProps { border?: number | string; @@ -63,8 +63,7 @@ export interface CardProps extends BoxProps { opacity?: number; variant?: string; } -type CardClass = React.StatelessComponent; -export declare const Card: CardClass; +export const Card: React.FunctionComponent; export interface FlexProps extends BoxProps { alignItems?: string; @@ -72,8 +71,7 @@ export interface FlexProps extends BoxProps { flexDirection?: string; flexWrap?: string; } -type FlexClass = React.StatelessComponent; -export declare const Flex: FlexClass; +export const Flex: React.FunctionComponent; export interface ImageProps extends BoxProps { height?: number | string; @@ -81,14 +79,12 @@ export interface ImageProps extends BoxProps { src?: string; alt?: string; } -type ImageClass = React.StatelessComponent; -export declare const Image: ImageClass; +export const Image: React.FunctionComponent; export interface LinkProps extends BoxProps { href?: string; } -type LinkClass = React.StatelessComponent; -export declare const Link: LinkClass; +export const Link: React.FunctionComponent; export interface TextProps extends BoxProps { fontSize?: number | ReadonlyArray; @@ -99,9 +95,7 @@ export interface TextProps extends BoxProps { lineHeight?: number | string; letterSpacing?: number | string; } -type TextClass = React.StatelessComponent; -export declare const Text: TextClass; +export const Text: React.FunctionComponent; -export interface HeadingProps extends TextProps {} -type HeadingClass = React.StatelessComponent; -export declare const Heading: HeadingClass; +export type HeadingProps = TextProps; +export const Heading: React.FunctionComponent; diff --git a/types/rebass/rebass-tests.tsx b/types/rebass/rebass-tests.tsx index fb0eae1ed4..53735775ff 100644 --- a/types/rebass/rebass-tests.tsx +++ b/types/rebass/rebass-tests.tsx @@ -1,8 +1,8 @@ -import * as React from 'react' -import { Box, Flex, Text, Heading, Button, Link, Image, Card } from 'rebass' +import * as React from 'react'; +import { Box, Flex, Text, Heading, Button, Link, Image, Card } from 'rebass'; -const RebassTests = () => ( - +() => ( + Hi, I'm a heading. @@ -32,4 +32,4 @@ const RebassTests = () => ( -) +); diff --git a/types/rebass/tslint.json b/types/rebass/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/rebass/tslint.json +++ b/types/rebass/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From c2627760b9a77adb447524da1fca719cda319987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20D=C3=BCfel?= Date: Mon, 28 Jan 2019 22:07:58 +0100 Subject: [PATCH 137/312] Add type definitions for fastify-rate-limit --- .../fastify-rate-limit-tests.ts | 22 ++++++ types/fastify-rate-limit/index.d.ts | 74 +++++++++++++++++++ types/fastify-rate-limit/package.json | 6 ++ types/fastify-rate-limit/tsconfig.json | 21 ++++++ types/fastify-rate-limit/tslint.json | 1 + 5 files changed, 124 insertions(+) create mode 100644 types/fastify-rate-limit/fastify-rate-limit-tests.ts create mode 100644 types/fastify-rate-limit/index.d.ts create mode 100644 types/fastify-rate-limit/package.json create mode 100644 types/fastify-rate-limit/tsconfig.json create mode 100644 types/fastify-rate-limit/tslint.json diff --git a/types/fastify-rate-limit/fastify-rate-limit-tests.ts b/types/fastify-rate-limit/fastify-rate-limit-tests.ts new file mode 100644 index 0000000000..ee79951f48 --- /dev/null +++ b/types/fastify-rate-limit/fastify-rate-limit-tests.ts @@ -0,0 +1,22 @@ +import fastifyRateLimit = require("fastify-rate-limit"); +import * as IORedis from 'ioredis'; +import { FastifyRequest, DefaultQuery } from "fastify"; +import { IncomingMessage } from "http"; + +fastifyRateLimit(); + +const fastifyRateLimitOptions: fastifyRateLimit.FastifyRateLimitOptions> = { + max: 3, + timeWindow: 5000, + cache: 10000, + whitelist: ['127.0.0.1'], + redis: new IORedis({ host: '127.0.0.1' }), + skipOnError: true, // default false + keyGenerator: (req) => { + return req.headers['x-real-ip'] + || req.headers['x-client-ip'] + || req.headers['x-forwarded-for'] + || req.params.test + || req.ip; + }, +}; diff --git a/types/fastify-rate-limit/index.d.ts b/types/fastify-rate-limit/index.d.ts new file mode 100644 index 0000000000..888611ad72 --- /dev/null +++ b/types/fastify-rate-limit/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for fastify-rate-limit 2.0 +// Project: https://github.com/fastify/fastify-rate-limit#readme +// Definitions by: Christian D +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Redis } from "ioredis"; +import { FastifyRequest } from "fastify"; +import { IncomingMessage } from "http"; + +declare function fastifyRateLimit(): void; + +declare namespace fastifyRateLimit { + interface FastifyRateLimitOptions> { + /** + * Is the maximum number of requests a single client can perform inside a + * timeWindow. + * + * default: 1000 + */ + max?: number; + + /** + * The duration of the time window, can be expressed in milliseconds (as a + * number) or as a string, see ms too see the supported formats + * + * default: 1000 * 60 + */ + timeWindow?: number; + + /** + * This plugin internally uses a lru cache to handle the clients, you can + * change the size of the cache with this option. + * + * default: 5000 + */ + cache?: number; + + /** + * Array of string of ips to exclude from rate limiting. + * + * default: [] + */ + whitelist?: string[]; + + /** + * By default this plugins uses an in-memory store, which is fast but if + * you application works on more than one server it is useless, since the + * data is store locally. You can pass a Redis client here and magically + * the issue is solved. To achieve the maximum speed, this plugins requires + * the use of ioredis. + * + * default: null + */ + redis?: Redis; + + /** + * If `true` it will skip errors generated by the storage (eg, redis not + * reachable). + * + * default: false + */ + skipOnError?: boolean; + + /** + * Function to generate a unique identifier for each incoming request. + * + * default: (req) => req.ip + */ + keyGenerator?: (req: T) => string; + } +} + +export = fastifyRateLimit; diff --git a/types/fastify-rate-limit/package.json b/types/fastify-rate-limit/package.json new file mode 100644 index 0000000000..e8c68ab969 --- /dev/null +++ b/types/fastify-rate-limit/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "fastify": "^1.11.2" + } +} diff --git a/types/fastify-rate-limit/tsconfig.json b/types/fastify-rate-limit/tsconfig.json new file mode 100644 index 0000000000..5dc0e91ea2 --- /dev/null +++ b/types/fastify-rate-limit/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", "fastify-rate-limit-tests.ts"], + "exclude": ["node-modules"] +} diff --git a/types/fastify-rate-limit/tslint.json b/types/fastify-rate-limit/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 407d5f293810dc070c61172f75b31f8565bcafed Mon Sep 17 00:00:00 2001 From: Akshay Karthik Date: Mon, 28 Jan 2019 14:50:26 -0500 Subject: [PATCH 138/312] [moo] Add type definitions for keywords value transform --- types/moo/index.d.ts | 19 +++++++++++++++---- types/moo/moo-tests.ts | 9 +++++---- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/types/moo/index.d.ts b/types/moo/index.d.ts index fd53f98e0a..2dd1a4b4db 100644 --- a/types/moo/index.d.ts +++ b/types/moo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for moo 0.4 +// Type definitions for moo 0.5 // Project: https://github.com/tjvr/moo#readme // Definitions by: Nikita Litvin // Jörg Vehlow @@ -11,6 +11,15 @@ export as namespace moo; */ export const error: { error: true }; +/** + * Reserved token for indicating a fallback rule. + */ +export const fallback: { fallback: true }; + +export type TypeMapper = (x: string) => string; + +export function keywords(kws: {[k: string]: string | string[]}): TypeMapper; + export function compile(rules: Rules): Lexer; export function states(states: {[x: string]: Rules}, start?: string): Lexer; @@ -45,9 +54,11 @@ export interface Rule { */ value?: (x: string) => string; - keywords?: { - [x: string]: string | string[] - }; + /** + * Used for mapping one set of types to another. + * See https://github.com/no-context/moo#keywords for an example + */ + type?: TypeMapper; } export interface Rules { [x: string]: RegExp | string | string[] | Rule | Rule[]; diff --git a/types/moo/moo-tests.ts b/types/moo/moo-tests.ts index c82bedd219..5cb9fa6f5b 100644 --- a/types/moo/moo-tests.ts +++ b/types/moo/moo-tests.ts @@ -20,20 +20,21 @@ lexer = moo.compile({ lexer = moo.compile({ IDEN: { - match: /[a-zA-Z]+/, keywords: { + match: /[a-zA-Z]+/, + type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'reloacows'] - } + }) }, SPACE: { match: /\s+/, lineBreaks: true } }); lexer = moo.compile({ name: { - match: /[a-zA-Z]+/, keywords: { + match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', - } + }) } }); From 892d33de44507c96f13eea2ab1b6605f19771929 Mon Sep 17 00:00:00 2001 From: Sebastian Vera Date: Mon, 28 Jan 2019 23:33:22 +0100 Subject: [PATCH 139/312] Add type definitions for @mapbox/s3urls --- types/mapbox__s3urls/index.d.ts | 33 ++++++++++++++++++++ types/mapbox__s3urls/mapbox__s3urls-tests.ts | 15 +++++++++ types/mapbox__s3urls/tsconfig.json | 19 +++++++++++ types/mapbox__s3urls/tslint.json | 1 + 4 files changed, 68 insertions(+) create mode 100644 types/mapbox__s3urls/index.d.ts create mode 100644 types/mapbox__s3urls/mapbox__s3urls-tests.ts create mode 100644 types/mapbox__s3urls/tsconfig.json create mode 100644 types/mapbox__s3urls/tslint.json diff --git a/types/mapbox__s3urls/index.d.ts b/types/mapbox__s3urls/index.d.ts new file mode 100644 index 0000000000..523cb0fc07 --- /dev/null +++ b/types/mapbox__s3urls/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for mapbox__s3urls 1.5 +// Project: https://github.com/mapbox/s3urls +// Definitions by: Sebastian Vera +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// tslint:disable-next-line no-single-declare-module +declare module "@mapbox/s3urls" { + function fromUrl( + url: string + ): { Bucket: string | undefined; Key: string | undefined }; + + function toUrl( + bucket: string, + key: string + ): { + s3: string; + "bucket-in-path": string; + "bucket-in-host": string; + }; + + function convert( + url: string, + to: "s3" | "bucket-in-path" | "bucket-in-host" + ): string; + + function signed( + url: string, + expires: number, + cb: (err: Error | undefined, url: string) => void + ): void; + + function valid(url: string): boolean; +} diff --git a/types/mapbox__s3urls/mapbox__s3urls-tests.ts b/types/mapbox__s3urls/mapbox__s3urls-tests.ts new file mode 100644 index 0000000000..7a50fdcfac --- /dev/null +++ b/types/mapbox__s3urls/mapbox__s3urls-tests.ts @@ -0,0 +1,15 @@ +import * as s3urls from "@mapbox/s3urls"; + +s3urls.toUrl("bucket", "key"); // $ExpectType { s3: string; "bucket-in-path": string; "bucket-in-host": string; } +s3urls.toUrl("bucket", "key")["s3"]; // $ExpectType string +s3urls.toUrl("bucket", "key")["bucket-in-host"]; // $ExpectType string +s3urls.toUrl("bucket", "key")["bucket-in-path"]; // $ExpectType string + +s3urls.valid("s3://bucket/key"); // $ExpectType boolean +s3urls.valid("invalid"); // $ExpectType boolean + +s3urls.convert("s3://bucket/key", "s3"); // $ExpectType string +s3urls.convert("s3://bucket/key", "bucket-in-path"); // $ExpectType string +s3urls.convert("s3://bucket/key", "bucket-in-host"); // $ExpectType string + +s3urls.fromUrl("s3://bucket/key"); // $ExpectType object diff --git a/types/mapbox__s3urls/tsconfig.json b/types/mapbox__s3urls/tsconfig.json new file mode 100644 index 0000000000..9c3d217340 --- /dev/null +++ b/types/mapbox__s3urls/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "paths": { + "@mapbox/s3urls": ["mapbox__s3urls"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mapbox__s3urls-tests.ts"] +} diff --git a/types/mapbox__s3urls/tslint.json b/types/mapbox__s3urls/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mapbox__s3urls/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From a501301d9d940abb3c387effc2e7c19650da6542 Mon Sep 17 00:00:00 2001 From: Luuk Sommers Date: Mon, 28 Jan 2019 23:43:05 +0100 Subject: [PATCH 140/312] webpack-env: Fix missing mode argument in require.context --- types/webpack-env/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webpack-env/index.d.ts b/types/webpack-env/index.d.ts index d9047f965e..0fde1243f4 100644 --- a/types/webpack-env/index.d.ts +++ b/types/webpack-env/index.d.ts @@ -32,7 +32,7 @@ declare namespace __WebpackModuleApi { * This creates a chunk. The chunk can be named. If a chunk with this name already exists, the dependencies are merged into that chunk and that chunk is used. */ ensure(paths: string[], callback: (require: NodeRequire) => void, errorCallback?: (error: any) => void, chunkName?: string): void; - context(path: string, deep?: boolean, filter?: RegExp): RequireContext; + context(path: string, deep?: boolean, filter?: RegExp, mode?: string): RequireContext; /** * Returns the module id of a dependency. The call is sync. No request to the server is fired. The compiler ensures that the dependency is available. * From 28628363db3b4e6a4cd021b0e338ed2b59d16641 Mon Sep 17 00:00:00 2001 From: Ruslan Hrabovyi Date: Tue, 29 Jan 2019 00:52:25 +0200 Subject: [PATCH 141/312] [@ember/string] Use type predicate as "isHTMLSafe" result --- types/ember__string/ember__string-tests.ts | 10 +++++++++- types/ember__string/index.d.ts | 4 ++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/types/ember__string/ember__string-tests.ts b/types/ember__string/ember__string-tests.ts index 1f045b849d..500c67546e 100644 --- a/types/ember__string/ember__string-tests.ts +++ b/types/ember__string/ember__string-tests.ts @@ -1,4 +1,4 @@ -import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } from '@ember/string'; +import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w, isHTMLSafe } from '@ember/string'; import { SafeString } from 'handlebars'; dasherize(); // $ExpectError @@ -36,3 +36,11 @@ loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string const handlebarsSafeString: SafeString = htmlSafe('lorem ipsum...'); htmlSafe('lorem ipsum...'); // $ExpectType SafeString const regularString: string = htmlSafe('lorem ipsum...'); // $ExpectError + +function isSafeTest(a: string|Handlebars.SafeString) { + if (isHTMLSafe(a)) { + a = a.toString(); + } + + camelize(a); +} diff --git a/types/ember__string/index.d.ts b/types/ember__string/index.d.ts index 8a2a46c022..66b5199bfd 100644 --- a/types/ember__string/index.d.ts +++ b/types/ember__string/index.d.ts @@ -11,8 +11,8 @@ export function capitalize(str: string): string; export function classify(str: string): string; export function dasherize(str: string): string; export function decamelize(str: string): string; -export function htmlSafe(str: string): Handlebars.SafeString; -export function isHTMLSafe(str: string): boolean; +export function htmlSafe(str: string): SafeString; +export function isHTMLSafe(str: any): str is SafeString; export function loc(template: string, args?: string[]): string; export function underscore(str: string): string; export function w(str: string): string[]; From 71bd0ba07bc8a99bd413d5c631f0daefb72014c1 Mon Sep 17 00:00:00 2001 From: Dan <32849715+ddangelo-shoprunner@users.noreply.github.com> Date: Mon, 28 Jan 2019 18:11:49 -0500 Subject: [PATCH 142/312] auth0-js - Including optional props AuthorizeOptions - acccessType; approvalPrompt (#32520) * Including optional properties AuthorizeOptions - acccessType; approvalForce auth-0.js actually forwards any param you send it (minus a specific black list). Auth0 Support and Community use these optional params, although they are not specifically called out in the Auth0 API documentation. Auth0 Support and Community even specify these are needed especially to get Google refresh_tokens (vie email Support Ticket, as well as the Community link below) https://community.auth0.com/t/cant-get-google-refresh-token-using-auth0-js/11756 * Corrected to use field approvalPrompt * fixed typo --- types/auth0-js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index a38c928333..f2cc95105c 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -812,6 +812,8 @@ export interface AuthorizeOptions { login_hint?: string; prompt?: string; mode?: "login" | "signUp"; + acccessType?: string; + approvalPrompt?: string; } export interface CheckSessionOptions extends AuthorizeOptions { From 78feba777260833b6e8a328c7ed8888bb6580849 Mon Sep 17 00:00:00 2001 From: Borewit Date: Tue, 29 Jan 2019 00:14:15 +0100 Subject: [PATCH 143/312] Needle: export NeedleResponse (#32535) * Export NeedleResponse * simply 'NeedleResponse' type test, get rid of function --- types/needle/index.d.ts | 1 + types/needle/needle-tests.ts | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/types/needle/index.d.ts b/types/needle/index.d.ts index 509e212c6e..af879cfacc 100644 --- a/types/needle/index.d.ts +++ b/types/needle/index.d.ts @@ -247,6 +247,7 @@ declare namespace needle { export type NeedleCallback = core.NeedleCallback; export type NeedleHttpVerbs = core.NeedleHttpVerbs; export type NeedleOptions = core.NeedleOptions; + export type NeedleResponse = core.NeedleResponse; export type ReadableStream = core.ReadableStream; /** diff --git a/types/needle/needle-tests.ts b/types/needle/needle-tests.ts index a216b1f686..fac7efa58c 100644 --- a/types/needle/needle-tests.ts +++ b/types/needle/needle-tests.ts @@ -73,14 +73,18 @@ function API_head() { function API_get() { // using promises + let resp: needle.NeedleResponse; + needle('get', 'google.com/search?q=syd+barrett') - .then((resp) => { + .then((_resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; }); // using callback - needle.get('google.com/search?q=syd+barrett', (err, resp) => { + needle.get('google.com/search?q=syd+barrett', (err, _resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; // assign response }); } From 4a91c57f19a024a9c273e5151bd482eca4fd44b4 Mon Sep 17 00:00:00 2001 From: AntoineC Date: Tue, 29 Jan 2019 00:16:51 +0100 Subject: [PATCH 144/312] Add Settings interface (#32352) Add test for settings on paper and new created PaperScope instance --- types/paper/index.d.ts | 48 +++++++++++++++++--------------------- types/paper/paper-tests.ts | 4 ++++ 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 6c1f2979fb..08a6d794ad 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -21,26 +21,7 @@ declare module paper { /** * Gives access to paper's configurable settings. */ - export var settings: { - - /** - * controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true - */ - insertItems: boolean; - /** - * controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true - */ - applyMatrix: boolean; - /** - * the size of the curve handles when drawing selections — default: 4 - */ - handleSize: number; - /* - * the default tolerance for hit- tests, when no value is specified — default: 0 - */ - hitTolerance: number; - - }; + export var settings: Settings; /** * The currently active project. @@ -1163,13 +1144,7 @@ declare module paper { /** * Gives access to paper's configurable settings. */ - settings: { - - applyMatrix: boolean; - handleSize: number; - hitTolerance: number; - - }; + settings: Settings; /** * The currently active project. @@ -5481,6 +5456,25 @@ declare module paper { type: 'mousedown' | 'mouseup' | 'mousedrag' | 'click' | 'doubleclick' | 'mousemove' | 'mouseenter' | 'mouseleave'; } + + export interface Settings { + /** + * controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true + */ + insertItems: boolean; + /** + * controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true + */ + applyMatrix: boolean; + /** + * the size of the curve handles when drawing selections — default: 4 + */ + handleSize: number; + /* + * the default tolerance for hit- tests, when no value is specified — default: 0 + */ + hitTolerance: number; + } } declare module 'paper' diff --git a/types/paper/paper-tests.ts b/types/paper/paper-tests.ts index 1d1bc32abe..280b68c0e9 100644 --- a/types/paper/paper-tests.ts +++ b/types/paper/paper-tests.ts @@ -81,6 +81,10 @@ hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceFull) paper.view.scaling = new paper.Point(1, 1); +paper.settings.insertItems = true +const paperScope = new paper.PaperScope(); +paperScope.settings.insertItems = false; + function Examples() { function BooleanOperations(){ let text = new paper.PointText({ From 9111fc377a85d84837d51f5096802669021cc9d0 Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Mon, 28 Jan 2019 23:17:53 +0000 Subject: [PATCH 145/312] [vinyl-fs] Add v0.3 and v1.0... Fix tslint rules and tests --- types/vinyl-fs/tslint.json | 5 +---- types/vinyl-fs/v0/tslint.json | 5 +---- types/vinyl-fs/v0/vinyl-fs-tests.ts | 6 +++--- types/vinyl-fs/v1/tslint.json | 5 +---- types/vinyl-fs/v1/vinyl-fs-tests.ts | 14 +++++++------- types/vinyl-fs/vinyl-fs-tests.ts | 14 +++++++------- 6 files changed, 20 insertions(+), 29 deletions(-) diff --git a/types/vinyl-fs/tslint.json b/types/vinyl-fs/tslint.json index f2821adb2b..f93cf8562a 100644 --- a/types/vinyl-fs/tslint.json +++ b/types/vinyl-fs/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json" } diff --git a/types/vinyl-fs/v0/tslint.json b/types/vinyl-fs/v0/tslint.json index f2821adb2b..f93cf8562a 100644 --- a/types/vinyl-fs/v0/tslint.json +++ b/types/vinyl-fs/v0/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json" } diff --git a/types/vinyl-fs/v0/vinyl-fs-tests.ts b/types/vinyl-fs/v0/vinyl-fs-tests.ts index b6aa418130..4d0316a0a0 100644 --- a/types/vinyl-fs/v0/vinyl-fs-tests.ts +++ b/types/vinyl-fs/v0/vinyl-fs-tests.ts @@ -383,7 +383,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -424,7 +424,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -467,7 +467,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats diff --git a/types/vinyl-fs/v1/tslint.json b/types/vinyl-fs/v1/tslint.json index f2821adb2b..f93cf8562a 100644 --- a/types/vinyl-fs/v1/tslint.json +++ b/types/vinyl-fs/v1/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json" } diff --git a/types/vinyl-fs/v1/vinyl-fs-tests.ts b/types/vinyl-fs/v1/vinyl-fs-tests.ts index aac3c4f49e..5b29b0465d 100644 --- a/types/vinyl-fs/v1/vinyl-fs-tests.ts +++ b/types/vinyl-fs/v1/vinyl-fs-tests.ts @@ -383,7 +383,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -424,7 +424,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -467,7 +467,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -711,7 +711,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -752,7 +752,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -795,7 +795,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -870,7 +870,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); diff --git a/types/vinyl-fs/vinyl-fs-tests.ts b/types/vinyl-fs/vinyl-fs-tests.ts index 18afe59744..2a38bcf811 100644 --- a/types/vinyl-fs/vinyl-fs-tests.ts +++ b/types/vinyl-fs/vinyl-fs-tests.ts @@ -383,7 +383,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -424,7 +424,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -467,7 +467,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -711,7 +711,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -752,7 +752,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -795,7 +795,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -870,7 +870,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); From 42e879f2223be2d15023d1c04d16d68d55b04726 Mon Sep 17 00:00:00 2001 From: Igor Goldvekht Date: Mon, 28 Jan 2019 18:20:14 -0500 Subject: [PATCH 146/312] [snoowrap] Fix typings for some Promise returning functions (#32505) * Fix typings for some Promise returning functions * Add semicolon --- types/snoowrap/dist/objects/LiveThread.d.ts | 4 +- types/snoowrap/dist/objects/RedditUser.d.ts | 16 +++---- types/snoowrap/dist/objects/Submission.d.ts | 5 +-- types/snoowrap/dist/objects/Subreddit.d.ts | 46 ++++++++++----------- types/snoowrap/dist/objects/WikiPage.d.ts | 4 +- types/snoowrap/snoowrap-tests.ts | 4 ++ 6 files changed, 41 insertions(+), 38 deletions(-) diff --git a/types/snoowrap/dist/objects/LiveThread.d.ts b/types/snoowrap/dist/objects/LiveThread.d.ts index ba34886fbb..594fc50247 100644 --- a/types/snoowrap/dist/objects/LiveThread.d.ts +++ b/types/snoowrap/dist/objects/LiveThread.d.ts @@ -26,8 +26,8 @@ export default class LiveThread extends RedditContent { deleteUpdate(options: { id: string; }): Promise; editSettings(options: LiveThreadSettings): Promise; getContributors(): Promise; - getDiscussions(options?: ListingOptions): Listing; - getRecentUpdates(options?: ListingOptions): Listing; + getDiscussions(options?: ListingOptions): Promise>; + getRecentUpdates(options?: ListingOptions): Promise>; inviteContributor(options: { name: string; permissions: Permissions[]}): Promise; leaveContributor(): Promise; removeContributor(options: { name: string; }): Promise; diff --git a/types/snoowrap/dist/objects/RedditUser.d.ts b/types/snoowrap/dist/objects/RedditUser.d.ts index a93cac98cd..35bc56eb9e 100644 --- a/types/snoowrap/dist/objects/RedditUser.d.ts +++ b/types/snoowrap/dist/objects/RedditUser.d.ts @@ -100,18 +100,18 @@ export default class RedditUser extends RedditContent { assignFlair(options: any): Promise; friend(options: any): Promise; - getComments(options?: any): Listing; - getDownvotedContent(options?: any): Listing; + getComments(options?: any): Promise>; + getDownvotedContent(options?: any): Promise>; getFriendInformation(): Promise; - getGildedContent(options?: any): Listing; - getHiddenContent(options?: any): Listing; + getGildedContent(options?: any): Promise>; + getHiddenContent(options?: any): Promise>; getMultireddit(name: string): MultiReddit; getMultireddits(): Promise; - getOverview(options?: any): Listing; - getSavedContent(options?: any): Listing; - getSubmissions(options?: any): Listing; + getOverview(options?: any): Promise>; + getSavedContent(options?: any): Promise>; + getSubmissions(options?: any): Promise>; getTrophies(): Promise; - getUpvotedContent(options?: any): Listing; + getUpvotedContent(options?: any): Promise>; giveGold(months: string): Promise; unfriend(): Promise; } diff --git a/types/snoowrap/dist/objects/Submission.d.ts b/types/snoowrap/dist/objects/Submission.d.ts index e2e7dc78d1..5986ac59cc 100644 --- a/types/snoowrap/dist/objects/Submission.d.ts +++ b/types/snoowrap/dist/objects/Submission.d.ts @@ -1,8 +1,7 @@ import { Sort } from '../..'; import Comment from './Comment'; import Listing, { ListingOptions } from './Listing'; -import RedditUser from './RedditUser'; -import Subreddit, { FlairTemplate } from './Subreddit'; +import { FlairTemplate } from './Subreddit'; import VoteableContent, { RichTextFlair } from './VoteableContent'; interface Media { @@ -113,7 +112,7 @@ export default class Submission extends VoteableContent { assignFlair(options: { text: string; cssClass: string; }): Promise; disableContestMode(): Promise; enableContestMode(): Promise; - getDuplicates(options?: ListingOptions): Listing; + getDuplicates(options?: ListingOptions): Promise>; getLinkFlairTemplates(): Promise; /* @deprecated */ getRelated(options?: ListingOptions): Submission; hide(): Promise; diff --git a/types/snoowrap/dist/objects/Subreddit.d.ts b/types/snoowrap/dist/objects/Subreddit.d.ts index 67623a17af..a9de52632d 100644 --- a/types/snoowrap/dist/objects/Subreddit.d.ts +++ b/types/snoowrap/dist/objects/Subreddit.d.ts @@ -1,12 +1,12 @@ -import { Sort, ModAction, SubmitSelfPostOptions, SubmitLinkOptions, BaseSearchOptions } from '../..'; +import { BaseSearchOptions, ModAction, Sort, SubmitLinkOptions, SubmitSelfPostOptions } from '../..'; import Comment from './Comment'; import Listing, { ListingOptions } from './Listing'; import PrivateMessage from './PrivateMessage'; import RedditContent from './RedditContent'; import RedditUser from './RedditUser'; import Submission from './Submission'; -import WikiPage, { WikiPageRevision } from './WikiPage'; import { RichTextFlair } from './VoteableContent'; +import WikiPage, { WikiPageRevision } from './WikiPage'; export default class Subreddit extends RedditContent { accounts_active_is_fuzzed: boolean; @@ -108,40 +108,40 @@ export default class Subreddit extends RedditContent { deleteImage(options: { imageName: string; }): Promise; deleteUserFlair(name: string): Promise; editSettings(options: SubredditSettings): Promise; - getBannedUsers(options?: ListingOptions & { name?: string }): Listing; - getContributors(options?: ListingOptions & { name?: string }): Listing; - getControversial(options?: ListingOptions & { time?: string }): Listing; - getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getHot(options?: ListingOptions): Listing; + getBannedUsers(options?: ListingOptions & { name?: string }): Promise>; + getContributors(options?: ListingOptions & { name?: string }): Promise>; + getControversial(options?: ListingOptions & { time?: string }): Promise>; + getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getHot(options?: ListingOptions): Promise>; getLinkFlairTemplates(linkId: string): Promise; - getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Listing; + getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Promise>; getModerators(options?: ListingOptions & { name?: string }): RedditUser[]; - getModmail(options?: ListingOptions): Listing; - getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getMutedUsers(options?: ListingOptions & { name?: string }): Listing; + getModmail(options?: ListingOptions): Promise>; + getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getMutedUsers(options?: ListingOptions & { name?: string }): Promise>; getMyFlair(): Promise; - getNew(options?: ListingOptions): Listing; - getNewComments(options?: ListingOptions): Listing; + getNew(options?: ListingOptions): Promise>; + getNewComments(options?: ListingOptions): Promise>; getRandomSubmission(): Promise; getRecommendedSubreddits(options?: { omit?: string[]; }): Promise; - getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getRising(options?: ListingOptions): Listing; + getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getRising(options?: ListingOptions): Promise>; getRules(): Promise<{ rules: Rule[]; site_rules: string[] }>; getSettings(): Promise; - getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; + getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; getSticky(options?: { num?: number }): Promise; getStylesheet(): Promise; getSubmitText(): Promise; - getTop(options?: ListingOptions & { time?: Timespan }): Listing; - getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; + getTop(options?: ListingOptions & { time?: Timespan }): Promise>; + getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; getUserFlair(name: string): Promise; - getUserFlairList(options?: ListingOptions & { name?: string; }): Listing; + getUserFlairList(options?: ListingOptions & { name?: string; }): Promise>; getUserFlairTemplates(): Promise; - getWikiBannedUsers(options?: ListingOptions & { name?: string }): Listing; - getWikiContributors(options?: ListingOptions & { name?: string }): Listing; + getWikiBannedUsers(options?: ListingOptions & { name?: string }): Promise>; + getWikiContributors(options?: ListingOptions & { name?: string }): Promise>; getWikiPage(name: string): WikiPage; getWikiPages(): Promise; - getWikiRevisions(options?: ListingOptions): Listing; + getWikiRevisions(options?: ListingOptions): Promise>; hideMyFlair(): Promise; inviteModerator(options: { name: string; permissions?: ModeratorPermission[]; }): Promise; leaveContributor(): Promise; @@ -151,7 +151,7 @@ export default class Subreddit extends RedditContent { removeModerator(options: { name: string; }): Promise; removeWikiContributor(options: { name: string; }): Promise; revokeModeratorInvite(options: { name: string; }): Promise; - search(options: BaseSearchOptions): Listing; + search(options: BaseSearchOptions): Promise>; selectMyFlair(options: { flair_template_id: string; text?: string; }): Promise; setModeratorPermissions(options: { name: string; permissions: ModeratorPermission; }): Promise; setMultipleUserFlairs(flairs: Array<{ diff --git a/types/snoowrap/dist/objects/WikiPage.d.ts b/types/snoowrap/dist/objects/WikiPage.d.ts index ab9de1bdf6..88f16e2f23 100644 --- a/types/snoowrap/dist/objects/WikiPage.d.ts +++ b/types/snoowrap/dist/objects/WikiPage.d.ts @@ -13,8 +13,8 @@ export default class WikiPage extends RedditContent { addEditor(options: { name: string; }): Promise; edit(options: EditOptions): Promise; editSettings(options: Settings): Promise; - getDiscussions(options?: ListingOptions): Listing; - getRevisions(options?: ListingOptions): Listing; + getDiscussions(options?: ListingOptions): Promise>; + getRevisions(options?: ListingOptions): Promise>; getSettings(): Promise; hideRevision(options: { id: string; }): Promise; removeEditor(options: { name: string; }): Promise; diff --git a/types/snoowrap/snoowrap-tests.ts b/types/snoowrap/snoowrap-tests.ts index b83a9514f1..61aca46ffa 100644 --- a/types/snoowrap/snoowrap-tests.ts +++ b/types/snoowrap/snoowrap-tests.ts @@ -81,3 +81,7 @@ export function submissionSearch(query: string, subreddit: string): Promise> { return r.searchSubreddits({ query }); } + +export function getHotFromSubreddit(subreddit: string): Promise> { + return r.getSubreddit(subreddit).getHot({ limit: 10 }); +} From 7abf322d4eeed043575c2e9234c54ff2d693816f Mon Sep 17 00:00:00 2001 From: Martin Helmich Date: Tue, 29 Jan 2019 00:39:51 +0100 Subject: [PATCH 147/312] [vis] DataSet.get may return null + type parameter for DataSet.map (#32570) --- types/vis/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 84ff769270..187c01c9b7 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -459,7 +459,7 @@ export class DataSet { * @returns When no item is found, null is returned when a single item was requested, * and and empty Array is returned in case of multiple id's. */ - get(id: IdType, options?: DataSelectionOptions): T; + get(id: IdType, options?: DataSelectionOptions): T|null; /** * Get multiple items from the DataSet. @@ -494,7 +494,7 @@ export class DataSet { * @param [options] Optional options. * @returns The mapped items. */ - map(callback: (item: T, id: IdType) => any, options?: DataSelectionOptions): any[]; + map(callback: (item: T, id: IdType) => M, options?: DataSelectionOptions): M[]; /** * Find the item with maximum value of specified field. @@ -589,7 +589,7 @@ export interface DataSelectionOptions { /** * Order the items by a field name or custom sort function. */ - order?: string | any; + order?: string | ((a: T, b: T) => number); /** * Determine the type of output of the get function. @@ -597,7 +597,7 @@ export interface DataSelectionOptions { * The default returnType is an Array. * The Object type will return a JSON object with the ID's as keys. */ - returnType?: string; + returnType?: "Array" | "Object"; } export class DataView { From 2e803abbff20cb20cc6ba158d676304d1b3eeedd Mon Sep 17 00:00:00 2001 From: Dale Fenton Date: Mon, 28 Jan 2019 18:44:17 -0500 Subject: [PATCH 148/312] Add types for Menu.Divider and Menu.Header (#32299) * add Menu.Divider and Menu.Header to Menu class * remove csstype dependency, just grab it from React * update renderToken prop definition from v3.0 upgrade * add typings for and other exported Components, update tests * fix labelKey type to only allow for property names of an object where the value is a string * add ClearButton test --- types/react-bootstrap-typeahead/index.d.ts | 316 +++++++++++++++--- types/react-bootstrap-typeahead/package.json | 6 - .../react-bootstrap-typeahead-tests.tsx | 92 ++++- 3 files changed, 343 insertions(+), 71 deletions(-) delete mode 100644 types/react-bootstrap-typeahead/package.json diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 52f99825d5..2f1ad8b7be 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -4,37 +4,121 @@ // Rajab Shakirov // Paito Anderson // Andreas Richter +// Dale Fenton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 -// TODO: components +// TypeScript Version: 2.9 import * as React from 'react'; -import * as CSS from 'csstype'; +export type Omit = Pick>; +export type StringPropertyNames = { [K in keyof T]: T[K] extends string ? K : never }[keyof T]; -export interface TypeaheadFilterbyProps { - filterBy: string[]; - labelKey: (string | (() => void)); - multiple: boolean; - selected: any[]; - caseSensitive: boolean; - ignoreDiacritics: boolean; +/* --------------------------------------------------------------------------- + Constants and Enumerated Types +--------------------------------------------------------------------------- */ +export type TypeaheadModel = string|object; +export type TypeaheadBsSizes = 'large' | 'lg' | 'small' | 'sm'; +export type TypeaheadAlign = 'justify' | 'left' | 'right'; +// if options is an object, only let labelKey be a key of that object, whose value is a string +// or a custom label function that takes a single option and returns a string for the label +export type TypeaheadLabelKey = T extends object ? (StringPropertyNames | ((option: T) => string)) : never; +// don't allow onBlur, onChange, onFocus or onKeyDown as members of inputProps +// those props should be supplied directly to or +export interface InputProps extends Omit, 'onBlur'|'onChange'|'onFocus'|'onKeyDown'> { } + +/* --------------------------------------------------------------------------- + Typeahead Contexts +--------------------------------------------------------------------------- */ +export interface TypeaheadContext { + activeIndex?: number; + hintText?: string; + initialItem?: T; + isOnlyResult?: boolean; + onActiveItemChange?: (options: T) => void; + onAdd?: (option: T) => void; + onInitialItemChange?: (option: T) => void; + onMenuItemClick?: (option: T, e: Event) => void; + selectHintOnEnter?: boolean; +} + +export interface TypeaheadState { + activeIndex: number|null; + activeItem: T|null; + initialItem: T|null; + isFocused: boolean; + selected: T[]; + showMenu: boolean; + shownResults: number; text: string; } -export interface TypeaheadMenuProps { +export interface InputContainerPropsSingle { + 'aria-activedescendant': string; + 'aria-autocomplete': 'list' | 'both'; + 'aria-expanded': boolean | 'true' | 'false'; + 'aria-haspopup': 'listbox'; + 'aria-owns': string; + autoComplete: string; + disabled: boolean; + inputRef: React.LegacyRef; + onBlur: (e: Event) => void; + onChange: (selected: T[]) => void; + onClick: (e: Event) => void; + onFocus: (e: Event) => void; + onKeyDown: (e: Event) => void; + placeholder: string|null; + role: 'combobox'; + value: string; +} + +export interface InputContainerPropsMultiple extends Omit, 'role'> { + inputClassName: string; + labelKey: TypeaheadLabelKey; + onRemove: (e: Event) => void; + renderToken: (selectedItem: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; + role: ''; + selected: T[]; +} + +export type HintedInputContextKeys = 'hintText' | 'initialItem' | 'onAdd' | 'selectHintOnEnter'; +export interface HintedInputContext extends Pick, HintedInputContextKeys> {} + +export type MenuItemContextKeys = 'activeIndex' | 'isOnlyResult' | 'onActiveItemChange' | 'onInitialItemChange' | 'onMenuItemClick'; +export interface MenuItemContext extends Pick, MenuItemContextKeys> {} + +export interface TokenContext { + active: boolean; + onBlur: (e: any) => void; + onClick: (e: any) => void; + onFocus: (e: any) => void; + onKeyDown: (e: any) => void; +} + +/* --------------------------------------------------------------------------- + Typeahead Props and Component +--------------------------------------------------------------------------- */ +export interface TypeaheadContainerProps { + activeIndex: number | null; + activeItem: T | null; + initialItem: T | null; + isFocused: boolean; + selected: T[]; + showMenu: boolean; + shownResults: number; text: string; } -export interface TypeaheadProps { - /* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */ +export interface TypeaheadProps { + /* For localized accessibility: Should return a string indicating the number of results for screen readers. + Receives the current results. */ a11yNumResults?: () => void; - /* For localized accessibility: Should return a string indicating the number of selections for screen readers. Receives the current selections. */ + /* For localized accessibility: Should return a string indicating the number of selections for screen readers. + Receives the current selections. */ a11yNumSelected?: () => void; /* Specify menu alignment. The default value is justify, which makes the menu as wide as the input and truncates long values. Specifying left or right will align the menu to that side and the width will be determined by the length of menu item values. */ - align?: 'justify' | 'left' | 'right'; + align?: TypeaheadAlign; /* Allows the creation of new selections on the fly. Any new items will be added to the list of selections, but not the list of original options unless handled as such by Typeahead's parent. @@ -49,7 +133,7 @@ export interface TypeaheadProps { bodyContainer?: boolean; /* Specify the size of the input. */ - bsSize?: 'large' | 'lg' | 'small' | 'sm'; + bsSize?: TypeaheadBsSizes; /* Whether or not filtering should be case-sensitive. */ caseSensitive?: boolean; @@ -60,6 +144,9 @@ export interface TypeaheadProps { /* The initial value displayed in the text input. */ defaultInputValue?: string; + /* Whether or not the menu is displayed upon initial render. */ + defaultOpen?: boolean; + /* Specify any pre-selected options. Use only if you want the component to be uncontrolled. */ defaultSelected?: T[]; @@ -74,7 +161,10 @@ export interface TypeaheadProps { emptyLabel?: string; /* Either an array of fields in option to search, or a custom filtering callback. */ - filterBy?: (string[] | ((option: T | string, props: TypeaheadFilterbyProps) => boolean)); + filterBy?: (string[] | ((option: T, props: AllTypeaheadOwnAndInjectedProps) => boolean)); + + /* Whether or not to automatically adjust the position of the menu when it reaches the viewport boundaries. */ + flip?: boolean; /* Highlights the menu item if there is only one result and allows selecting that item by hitting enter. Does not work with allowNew. */ @@ -84,7 +174,7 @@ export interface TypeaheadProps { ignoreDiacritics?: boolean; /* Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored. */ - inputProps?: object; + inputProps?: InputProps; /* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`. */ isInvalid?: boolean; @@ -95,8 +185,9 @@ export interface TypeaheadProps { /* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`. */ isValid?: boolean; - /* Specify which option key to use for display or a render function. By default, the selector will use the label key. */ - labelKey?: string | ((option: T | string) => string); + /* Specify which option key to use for display or a render function. + By default, the selector will use the label key. */ + labelKey?: TypeaheadLabelKey; /* Maximum height of the dropdown menu. */ maxHeight?: string; @@ -105,6 +196,9 @@ export interface TypeaheadProps { so as not to render too many DOM nodes in the case of large data sets. */ maxResults?: number; + /* Id applied to the top-level menu element. Required for accessibility. */ + menuId?: string; + /* Number of input characters that must be entered before showing results. */ minLength?: number; @@ -115,28 +209,35 @@ export interface TypeaheadProps { newSelectionPrefix?: string; /* Invoked when the input is blurred. Receives an event. */ - onBlur?: (e: Event) => any; + onBlur?: (e: Event) => void; /* Invoked whenever items are added or removed. Receives an array of the selected options. */ - onChange?: (selected: T[]) => any; + onChange?: (selected: T[]) => void; /* Invoked when the input is focused. Receives an event. */ - onFocus?: (e: Event) => any; + onFocus?: (e: Event) => void; /* Invoked when the input value changes. Receives the string value of the input, as well as the original event. */ - onInputChange?: (input: string, e: Event) => any; + onInputChange?: (input: string, e: Event) => void; /* Invoked when a key is pressed. Receives an event. */ - onKeyDown?: (e: Event) => any; + onKeyDown?: (e: Event) => void; - /* Invoked when the menu is hidden. */ - onMenuHide?: (e: Event) => any; + /* DEPRECATED: Invoked when the menu is hidden. */ + onMenuHide?: () => void; - /* Invoked when the menu is shown. */ - onMenuShow?: (e: Event) => any; + /* DEPRECATED: Invoked when the menu is shown. */ + onMenuShow?: () => void; + + /* Invoked when menu visibility changes. */ + onMenuToggle?: (show: boolean) => void; /* Invoked when the pagination menu item is clicked. */ - onPaginate?: (e: Event) => any; + onPaginate?: (e: Event, numResults: number) => void; + + /* Whether or not the menu should be displayed. undefined allows the component to control visibility, + while true and false show and hide the menu, respectively. */ + open?: boolean; /* Full set of options, including any pre-selected options. */ options: T[]; @@ -151,13 +252,13 @@ export interface TypeaheadProps { placeholder?: string; /* Callback for custom menu rendering. */ - renderMenu?: (results: Array, menuProps: any) => any; + renderMenu?: (results: T[], menuProps: any) => React.ReactNode; /* Provides a hook for customized rendering of menu item contents. */ - renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps, index: number) => any; + renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; /* Provides a hook for customized rendering of tokens when multiple selections are enabled. */ - renderToken?: (selectedItem: T | string, onRemove: () => void) => any; + renderToken?: (selectedItem: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; /* The selected option(s) displayed in the input. Use this prop if you want to control the component via its parent. */ selected?: T[]; @@ -166,9 +267,13 @@ export interface TypeaheadProps { selectHintOnEnter?: boolean; } -export const Typeahead: React.ClassicComponentClass>; +export type AllTypeaheadOwnAndInjectedProps = TypeaheadProps & TypeaheadContainerProps; +export class Typeahead extends React.Component> { } -export interface AsyncTypeaheadProps extends TypeaheadProps { +/* --------------------------------------------------------------------------- + AsyncTypeahead Props and Component +--------------------------------------------------------------------------- */ +export interface AsyncTypeaheadProps extends TypeaheadProps { /* Delay, in milliseconds, before performing search. */ delay?: number; @@ -179,45 +284,148 @@ export interface AsyncTypeaheadProps extends TypeaheadProps { onSearch: (query: string) => void; /* Message displayed in the menu when there is no user input. */ - promptText?: string; + promptText?: React.ReactNode; /* Message to display in the menu while the request is pending. */ - searchText?: string; + searchText?: React.ReactNode; /* Whether or not the component should cache query results. */ useCache?: boolean; } -export const AsyncTypeahead: React.ClassicComponentClass>; +export class AsyncTypeahead extends React.Component> { } -export interface HighligherProps { - key?: string; - search: string; - optionId?: any; +/* --------------------------------------------------------------------------- + TypeaheadInputSingle & TypeaheadInputMulti Props and Component +--------------------------------------------------------------------------- */ +export interface BaseTypeaheadInputProps extends React.InputHTMLAttributes<'input'> { + type: 'text'; } -export const Highlighter: React.ClassicComponentClass>; +export interface TypeaheadSingleInputWithHocProps extends + Omit>, + InputContainerPropsSingle {} -export interface MenuProps { +export interface TypeaheadMulitInputWithHocProps extends + Omit>, + HintedInputContext, + InputContainerPropsMultiple {} + +export type TypeaheadInputPropKeys = 'bsSize'|'disabled'|'inputProps'|'labelKey'|'multiple'| + 'onBlur'|'onChange'|'onFocus'|'onKeyDown'|'placeholder'|'renderToken'|'selected'; + +export type TypeaheadInputProps = Pick, TypeaheadInputPropKeys>; + +export class TypeaheadInputSingle extends React.Component> { } +export class TypeaheadInputMulti extends React.Component> { } + +/* --------------------------------------------------------------------------- + Highlighter Props and Component +--------------------------------------------------------------------------- */ +export interface HighligherProps { + children: React.ReactNode; + search: string; +} + +export class Highlighter extends React.PureComponent { } + +/* --------------------------------------------------------------------------- + ClearButton Props and Component +--------------------------------------------------------------------------- */ +export interface ClearButtonProps extends React.HTMLAttributes<'button'> { + bsSize?: TypeaheadBsSizes; + label?: string; + onClick: React.HTMLAttributes<'button'>['onClick']; // make onClick requried +} + +export const ClearButton: React.FunctionComponent; + +/* --------------------------------------------------------------------------- + Loader Props and Component +--------------------------------------------------------------------------- */ +export interface LoaderProps { + bsSize: TypeaheadBsSizes; +} + +export const Loader: React.FunctionComponent; + +/* --------------------------------------------------------------------------- + AutosizeInput Props and Component +--------------------------------------------------------------------------- */ +export interface AutosizeInputProps extends Pick, 'className' | 'style'> { + inputClassName?: string; + inputRef?: React.LegacyRef; + inputStyle?: Pick; + style: React.CSSProperties; +} + +export class AutosizeInput extends React.Component { } + +/* --------------------------------------------------------------------------- + Menu Props and Component +--------------------------------------------------------------------------- */ +export interface MenuProps { id: string; className?: string; emptyLabel?: string; - innerRef?: string; + innerRef?: React.LegacyRef; maxHeight?: string; - style?: CSS.Properties; + style?: React.CSSProperties; + text?: string; } -export const Menu: React.ClassicComponentClass>; +export type MenuHeaderProps = Omit, 'className'>; -export interface MenuItemProps { +export class Menu extends React.Component { + static Divider: React.FunctionComponent; + static Header: React.FunctionComponent; +} + +/* --------------------------------------------------------------------------- + TypeaheadMenu Props and Component +--------------------------------------------------------------------------- */ +// prop names that Typeahead provides to TypeaheadMenu +export type TypeaheadMenuPropsPick = 'labelKey' | 'newSelectionPrefix'| 'options' | 'renderMenuItemChildren'; +export interface TypeaheadMenuProps extends MenuProps, Pick, TypeaheadMenuPropsPick> {} +export class TypeaheadMenu extends React.Component> { } + +/* --------------------------------------------------------------------------- + Menu Item Props and Component +--------------------------------------------------------------------------- */ +export interface BaseMenuItemProps extends React.HTMLProps<'li'> { + active?: boolean; +} +export class BaseMenuItem extends React.Component { } + +export interface MenuItemProps extends BaseMenuItemProps { option: T; position: number; label?: string; - active?: boolean; - className?: string; - disabled?: boolean; - onClick?: (e: Event) => any; - onMouseDown?: (e: Event) => any; } -export const MenuItem: React.ClassicComponentClass>; +export class MenuItem extends React.Component> { } + +/* --------------------------------------------------------------------------- + Overlay Props and Component +--------------------------------------------------------------------------- */ +export type OverlayTypeaheadProps = Pick, 'align' | 'dropup' | 'flip' | 'onMenuHide' | 'onMenuShow' | 'onMenuToggle'>; + +export interface OverlayProps extends OverlayTypeaheadProps { + children?: React.ReactNode; + className?: string; + container: HTMLElement; + referenceElement?: HTMLElement; + show?: boolean; +} + +export class Overlay extends React.Component { } + +/* --------------------------------------------------------------------------- + Token Props and Component +--------------------------------------------------------------------------- */ +export interface TokenProps extends React.HTMLProps<'div'> { + active?: boolean; + onRemove?: () => void; // Token does not invoke onRemove with any parameters +} + +export class Token extends React.Component { } diff --git a/types/react-bootstrap-typeahead/package.json b/types/react-bootstrap-typeahead/package.json deleted file mode 100644 index e6696d08e7..0000000000 --- a/types/react-bootstrap-typeahead/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "private": true, - "dependencies": { - "csstype": "^2.2.0" - } -} diff --git a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx index c77052a3c6..7e2c3a29a6 100644 --- a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx +++ b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx @@ -1,25 +1,78 @@ import * as React from 'react'; -import { Typeahead, Highlighter, Menu, MenuItem } from 'react-bootstrap-typeahead'; +import { ClearButton, Typeahead, Highlighter, Menu, MenuItem, Token } from 'react-bootstrap-typeahead'; -const options = [ - { name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South' }, - { name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West' }, - { name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West' }, - { name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South' }, - { name: 'California', population: 37254503, capital: 'Sacramento', region: 'West' }, - { name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West' }, +interface State { + capital: string; + name: string; + population: number; + region: string; + setValue: (value: State) => void; +} +interface GroupedStates { + [key: string]: State[]; +} +type StringPropertyNames = { [K in keyof T]: T[K] extends string ? K : never }[keyof T]; +type StateKeysValid = StringPropertyNames; +const options: State[] = [ + { name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South', setValue: () => {} }, + { name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West', setValue: () => {} }, + { name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West', setValue: () => {} }, + { name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South', setValue: () => {} }, + { name: 'California', population: 37254503, capital: 'Sacramento', region: 'West', setValue: () => {} }, + { name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West', setValue: () => {} }, ]; +const stateNames = options.map(o => o.name); + +const groups: GroupedStates = options.reduce((accum: GroupedStates, option: State) => { + const optKey = option.name.slice(0, 1).toLowerCase(); + if (accum[optKey] !== undefined) { + accum[optKey].push(option); + } else { + accum[optKey] = [option]; + } + return accum; +}, {}); + class BasicExample extends React.Component { state = { multiple: false, }; + genCustomMenu = () => { + const menuItems = Object.keys(groups).reduce((accum, letter) => { + const header = [ + , + + {`States starting with: ${letter.toUpperCase()}`} + {}} /> + , + , + ]; + const states = groups[letter].map((state: State, index: number) => { + return ({state.name}); + }); + return [...accum, ...header, ...states]; + }, [] as JSX.Element[]); + + return menuItems; + } + render() { const { multiple } = this.state; return (
    + + (props.text.indexOf(option) !== -1)} + /> (props.text.indexOf(option) !== -1) } + filterBy={(option, props) => (props.text.indexOf(option.name) !== -1) } placeholder="Choose a state..." /> (text.indexOf(option) !== -1) } + filterBy={(option, {text}) => (text.indexOf(option.name) !== -1) } placeholder="Choose a state..." /> - + {option.name} {index} } @@ -69,6 +122,23 @@ class BasicExample extends React.Component { ))} + { + return console.log(props.text)}> + {selectedItem.name} {}} /> + ; + }} + > + {...this.genCustomMenu()} +
    ); } From a8f1326ba72ece5f12189e5c8006967a23c014be Mon Sep 17 00:00:00 2001 From: Kosaku Kurino Date: Tue, 29 Jan 2019 08:48:52 +0900 Subject: [PATCH 149/312] [types/recharts]Add index definitation in PieProps (#32441) * Add index definitation in PieProps I can not see the "index" parameter in the document, but it actually exists and I added it for frequent use when creating custom labels. document http://recharts.org/en-US/api/Pie * [types/recharts] add PieLabelRenderProps def PieLabelRenderProps extends PieProps * fix error add semi * update PieProps labels def ``` label?: { offsetRadius: number; } | React.ReactElement | ContentRenderer | boolean; ``` to: ``` label?: { offsetRadius: number; } | React.ReactElement | ContentRenderer | boolean; ``` * fix error ``` label?: { offsetRadius: number; } | React.ReactElement | ContentRenderer | boolean; ``` to: ``` label?: { offsetRadius: number; } | React.ReactElement | ContentRenderer | boolean; ``` * update PieLabelRenderProps properties add className * Edit PieRenderProps add name to PieLabelRenderProps. delete className from PieLabelRenderProps. * Update PieLabelRenderProps update PieLabelRenderProps' name property * add parameter to PieLabelRenderProps add parameter to PieLabelRenderProps --- types/recharts/index.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 426e74d6ba..fc127e9251 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -12,6 +12,7 @@ // Harry Cruse // Andrew Palugniok // Robert Stigsson +// Kosaku Kurino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -451,12 +452,23 @@ export interface PieProps extends EventAttributes, Partial | React.ReactElement | boolean; label?: { offsetRadius: number; - } | React.ReactElement | ContentRenderer | boolean; + } | React.ReactElement | ContentRenderer | boolean; activeShape?: object | ContentRenderer | React.ReactElement; activeIndex?: number | number[]; blendStroke?: boolean; } +export interface PieLabelRenderProps extends PieProps { + name: string; + percent?: number; + stroke: string; + index?: number; + textAnchor: string; + x: number; + y: number; + [key: string]: any; +} + export class Pie extends React.Component { } // NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). From e4e56293bb654185f89b49bcae4964068487b953 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Mon, 28 Jan 2019 16:10:49 -0800 Subject: [PATCH 150/312] Updates based on eng feedback --- types/office-js/index.d.ts | 65 +++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index ea804993a1..1b3f3c447a 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -7736,7 +7736,7 @@ declare namespace Office { /** * A conference room or similar resource. */ - ConferenceRoom = "conferenceRoom" + Room = "room" } /** * Specifies the month. @@ -9429,15 +9429,15 @@ declare namespace Office { * * In addition to this signature, this method also has the following signatures: * - * `addAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void;` + * `addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void;` * - * @param locationIds The locations to be added to the current list of locations. + * @param locationIdentifiers The locations to be added to the current list of locations. * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, - * asyncResult, which is an Office.AsyncResult object. + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. */ - addAsync(locationIds: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + addAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** * Adds to the set of locations associated with the appointment. * @@ -9453,11 +9453,11 @@ declare namespace Office { * * * - * @param locationIds The locations to be added to the current list of locations. + * @param locationIdentifiers The locations to be added to the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, - * asyncResult, which is an Office.AsyncResult object. + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. */ - addAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void; + addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; /** * Gets the set of locations associated with the appointment. * @@ -9469,7 +9469,7 @@ declare namespace Office { * * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} - * Compose + * Compose or read * * * @@ -9494,7 +9494,7 @@ declare namespace Office { * * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} - * Compose + * Compose or read * * * @@ -9505,10 +9505,7 @@ declare namespace Office { /** * Removes the set of locations associated with the appointment. * - * Any included conference rooms (i.e., in the `LocationDetails` object, the `type` is **ConferenceRoom** and there is an email address) - * should be removed from the locations and the resources lists. - * - * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIds. + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * * @remarks * @@ -9524,22 +9521,19 @@ declare namespace Office { * * In addition to this signature, this method also has the following signatures: * - * `removeAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void;` + * `removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void;` * - * @param locationIds The locations to be removed from the current list of locations. + * @param locationIdentifiers The locations to be removed from the current list of locations. * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, - * asyncResult, which is an Office.AsyncResult object. + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. */ - removeAsync(locationIds: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + removeAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** * Removes the set of locations associated with the appointment. * - * Any included conference rooms (i.e., in the `LocationDetails` object, the `type` is **ConferenceRoom** and there is an email address) - * should be removed from the locations and the resources lists. - * - * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIds. + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * * @remarks *
    @@ -9553,11 +9547,11 @@ declare namespace Office { * *
    * - * @param locationIds The locations to be removed from the current list of locations. + * @param locationIdentifiers The locations to be removed from the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, - * asyncResult, which is an Office.AsyncResult object. + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. */ - removeAsync(locationIds: LocationIdentifier[], callback?: (result: Office.AsyncResult) => void): void; + removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; } /** * Represents a collection of entities found in an email message or appointment. Read mode only. @@ -9833,9 +9827,9 @@ declare namespace Office { */ export interface LocationDetails { /** - * The location's id. + * The LocationIdentifier of the location. */ - locationId: LocationIdentifier; + locationIdentifier: LocationIdentifier; /** * The location's display name. */ @@ -9844,10 +9838,6 @@ declare namespace Office { * The email address associated with the location. */ emailAddress: string; - /** - * Additional properties for the location. - */ - properties: any; } /** @@ -9861,7 +9851,7 @@ declare namespace Office { /** * The location's unique id. * - * For **ConferenceRoom** type, it's the room's email address. + * For **Room** type, it's the room's email address. * * For **Custom** type, it's the displayName. */ @@ -9974,7 +9964,7 @@ declare namespace Office { */ end: Time; /** - * Gets or sets the locations of the appointment. The `enhancedLocations` property returns an {@link EnhancedLocation} object that + * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link EnhancedLocation} object that * provides methods to get, remove, or add locations on an item. * * [Api set: Mailbox Preview] @@ -9994,7 +9984,7 @@ declare namespace Office { * * @beta */ - enhancedLocations: EnhancedLocation; + enhancedLocation: EnhancedLocation; /** * Gets the type of item that an instance represents. * @@ -11083,7 +11073,10 @@ declare namespace Office { */ end: Date; /** - * Gets a set of LocationDetails objects that represents the locations of the appointment. + * Gets the locations of an appointment. + * + * The enhancedLocation property returns an {@link EnhancedLocation} object that allows you to get the set of locations (each represented by + * a {@link LocationDetails} object) associated with the appointment. * * [Api set: Mailbox Preview] * @@ -11102,7 +11095,7 @@ declare namespace Office { * * @beta */ - enhancedLocations: LocationDetails[]; + enhancedLocation: EnhancedLocation; /** * Gets the Exchange Web Services item class of the selected item. * From a345bad39bc7f14bf98254b92320028141c28781 Mon Sep 17 00:00:00 2001 From: Ryo Ota Date: Tue, 29 Jan 2019 09:13:40 +0900 Subject: [PATCH 151/312] [multiparty] Add types for multiparty.Form#on() methods and originalFilename renaming (#32440) * Add types for multiparty.Form#on() methods * Rename originalFileName to originalFilename --- types/multiparty/index.d.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/types/multiparty/index.d.ts b/types/multiparty/index.d.ts index ca968fefcf..1dbb3e272b 100644 --- a/types/multiparty/index.d.ts +++ b/types/multiparty/index.d.ts @@ -19,6 +19,13 @@ export declare class Form extends events.EventEmitter { * @param callback */ parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; + + on(event: "part", listener: (part: Part) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "progress", listener: (bytesReceived: number, bytesExpected: number) => void): this; + on(event: "field", listener: (name: string, value: string) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; } export interface File { @@ -29,7 +36,7 @@ export interface File { /** * the filename that the user reports for the file */ - originalFileName: string; + originalFilename: string; /** * the absolute path of the uploaded file on disk */ @@ -44,7 +51,7 @@ export interface File { size: number; } -interface Part extends stream.Readable { +export interface Part extends stream.Readable { /** * the headers for this part. For example, you may be interested in content-type */ From ea2b36990777f7e09cce172235770c6c9793210a Mon Sep 17 00:00:00 2001 From: Patrick Chatain Date: Tue, 29 Jan 2019 01:16:21 +0100 Subject: [PATCH 152/312] [Bull] Add missing getJobCountByTypes definition (#32514) * Add getJobCountByTypes definition * Update index.d.ts * getJobCountByTypes types can also be a string --- types/bull/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index b2fb68d4d7..bbafa0301c 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -585,6 +585,11 @@ declare namespace Bull { */ getJobCounts(): Promise; + /** + * Returns a promise that resolves with the job counts for the given queue of the given types. + */ + getJobCountByTypes(types: string[] | string): Promise; + /** * Returns a promise that resolves with the quantity of completed jobs. */ From df207da292a73fe824132c9bfad06359705160c2 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Mon, 28 Jan 2019 16:26:28 -0800 Subject: [PATCH 153/312] Add changes to office-js-preview --- types/office-js-preview/index.d.ts | 276 +++++++++++++++++++++++++++++ 1 file changed, 276 insertions(+) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 75e9ed910f..e26ab7e8a0 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -7713,6 +7713,31 @@ declare namespace Office { */ Appointment = "appointment" } + /** + * Specifies an appointment's location type. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * @beta + */ + enum LocationType { + /** + * A custom location. + */ + Custom = "custom", + /** + * A conference room or similar resource. + */ + Room = "room" + } /** * Specifies the month. * @@ -9367,6 +9392,167 @@ declare namespace Office { */ emailAddress: string; } + /** + * Represents the set of locations on an appointment. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * @beta + */ + interface EnhancedLocation { + /** + * Adds to the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * In addition to this signature, this method also has the following signatures: + * + * `addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void;` + * + * @param locationIdentifiers The locations to be added to the current list of locations. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + */ + addAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; + /** + * Adds to the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * @param locationIdentifiers The locations to be added to the current list of locations. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + */ + addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; + /** + * Gets the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * In addition to this signature, this method also has the following signatures: + * + * `getAsync(callback?: (result: Office.AsyncResult) => void): void;` + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + getAsync(options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Gets the set of locations associated with the appointment. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
    + * + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + */ + getAsync(callback?: (result: Office.AsyncResult) => void): void; + /** + * Removes the set of locations associated with the appointment. + * + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * In addition to this signature, this method also has the following signatures: + * + * `removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void;` + * + * @param locationIdentifiers The locations to be removed from the current list of locations. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + */ + removeAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; + /** + * Removes the set of locations associated with the appointment. + * + * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. + * + * @remarks + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    + * + * @param locationIdentifiers The locations to be removed from the current list of locations. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + */ + removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; + } /** * Represents a collection of entities found in an email message or appointment. Read mode only. * @@ -9632,6 +9818,50 @@ declare namespace Office { setAsync(headers: Object, callback?: (result: Office.AsyncResult) => void): void; } + /** + * Represents a location. Read only. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + export interface LocationDetails { + /** + * The LocationIdentifier of the location. + */ + locationIdentifier: LocationIdentifier; + /** + * The location's display name. + */ + displayName: string; + /** + * The email address associated with the location. + */ + emailAddress: string; + } + + /** + * Represents the id of a location. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + interface LocationIdentifier { + /** + * The location's unique id. + * + * For **Room** type, it's the room's email address. + * + * For **Custom** type, it's the displayName. + */ + id: string; + /** + * The location's type. + */ + type: MailboxEnums.LocationType; + } + /** * Represents the appointment organizer, even if an alias or a delegate was used to create the appointment. * This object provides a method to get the organizer value of an appointment in an Outlook add-in. @@ -9733,6 +9963,28 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer */ end: Time; + /** + * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link EnhancedLocation} object that + * provides methods to get, remove, or add locations on an item. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
    + * + * @beta + */ + enhancedLocation: EnhancedLocation; /** * Gets the type of item that an instance represents. * @@ -10820,6 +11072,30 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee */ end: Date; + /** + * Gets the locations of an appointment. + * + * The enhancedLocation property returns an {@link EnhancedLocation} object that allows you to get the set of locations (each represented by + * a {@link LocationDetails} object) associated with the appointment. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + * + * + * + * + * + *
    {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee
    + * + * @beta + */ + enhancedLocation: EnhancedLocation; /** * Gets the Exchange Web Services item class of the selected item. * From d762a2f314aaba34502bc7b515e4116322561408 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 24 Jan 2019 14:25:21 +0900 Subject: [PATCH 154/312] update diff types --- types/diff/diff-tests.ts | 25 +++++++++++++++++-------- types/diff/index.d.ts | 2 +- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 845b307132..ca00b1f458 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -86,18 +86,19 @@ function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.Parsed throw new Error('Patch did not match uniDiff'); } } -function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { +function verifyApplyMethods(oldStr: string, newStr: string, uniDiffStr: string) { + const uniDiff = diff.parsePatch(uniDiffStr)[0]; const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])]; - diff.applyPatches([uniDiff], { - loadFile: (index, callback) => { + const options: diff.ApplyPatchesOptions = { + loadFile(index, callback) { index; // $ExpectType ParsedDiff callback(undefined, one); }, - patched: (index, content) => { + patched(index, content) { index; // $ExpectType ParsedDiff verifyApply.push(content); }, - complete: (err?: Error) => { + complete(err) { if (err) { throw err; } @@ -108,7 +109,16 @@ function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.Parsed } }); }, - }); + compareLine(_, line, operator, patchContent) { + if (operator === ' ') { + return true; + } + return line === patchContent; + }, + fuzzFactor: 0 + }; + diff.applyPatches([uniDiff], options); + diff.applyPatches(uniDiffStr, options); } const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', { @@ -117,5 +127,4 @@ const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other verifyPatchMethods(one, other, uniDiffPatch); const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 }); -const uniDiffApply = diff.parsePatch(uniDiffStr)[0]; -verifyApplyMethods(one, other, uniDiffApply); +verifyApplyMethods(one, other, uniDiffStr); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index fa0e4e2e3d..5afb72192e 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -98,7 +98,7 @@ export interface ApplyPatchOptions { ) => boolean; } -export interface ApplyPatchesOptions { +export interface ApplyPatchesOptions extends ApplyPatchOptions { loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; complete(err: any): void; From 217244347fff7da3364c7bd9c04f6454bfd44835 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Tue, 29 Jan 2019 06:35:30 +0100 Subject: [PATCH 155/312] chore(defaults-deep): use spread parameters only --- types/defaults-deep/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts index b7583dd92e..a814ee0f4a 100644 --- a/types/defaults-deep/index.d.ts +++ b/types/defaults-deep/index.d.ts @@ -7,7 +7,7 @@ interface Obj { [k: string]: any; } -export default function defaultDeep(obj?: Obj, ...objs: Obj[]): Obj; +export default function defaultDeep(...objs: Obj[]): Obj; // strict-export-declare-modifiers export {}; From ba703b81164c5cf89fe15d2512cee8b798732d45 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Tue, 29 Jan 2019 06:53:42 +0100 Subject: [PATCH 156/312] fix(defaults-deep): fix export --- types/defaults-deep/defaults-deep-tests.ts | 2 +- types/defaults-deep/index.d.ts | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/types/defaults-deep/defaults-deep-tests.ts b/types/defaults-deep/defaults-deep-tests.ts index 826bbb4d0f..daabc46d7d 100644 --- a/types/defaults-deep/defaults-deep-tests.ts +++ b/types/defaults-deep/defaults-deep-tests.ts @@ -1,4 +1,4 @@ -import defaults from 'defaults-deep'; +import defaults = require('defaults-deep'); defaults(); defaults({a: 'foo'}); diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts index a814ee0f4a..749257eb88 100644 --- a/types/defaults-deep/index.d.ts +++ b/types/defaults-deep/index.d.ts @@ -7,7 +7,6 @@ interface Obj { [k: string]: any; } -export default function defaultDeep(...objs: Obj[]): Obj; +declare function defaultsDeep(...objs: Obj[]): Obj; -// strict-export-declare-modifiers -export {}; +export = defaultsDeep; From c21a33e1783ee706b9bbe118c6f5dc9f2844049c Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Tue, 29 Jan 2019 12:33:18 +0530 Subject: [PATCH 157/312] Type definitions for happypack --- types/happypack/index.d.ts | 21 +++++++++++++++++++++ types/happypack/tsconfig.json | 22 ++++++++++++++++++++++ types/happypack/tslint.json | 4 ++++ 3 files changed, 47 insertions(+) create mode 100644 types/happypack/index.d.ts create mode 100644 types/happypack/tsconfig.json create mode 100644 types/happypack/tslint.json diff --git a/types/happypack/index.d.ts b/types/happypack/index.d.ts new file mode 100644 index 0000000000..c42bdc1cf7 --- /dev/null +++ b/types/happypack/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for happypack +// Project: https://github.com/amireh/happypack +// Definitions by: Akash Vishwakarma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +declare class HappyPack extends Plugin { + + constructor(options?: HappyPack.PluginOptions); +} + +declare namespace HappyPack { + interface PluginOptions { + id?: string; + threads?: number; + loaders?: any; + } +} + +export = HappyPack; diff --git a/types/happypack/tsconfig.json b/types/happypack/tsconfig.json new file mode 100644 index 0000000000..b65889af68 --- /dev/null +++ b/types/happypack/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + ] +} diff --git a/types/happypack/tslint.json b/types/happypack/tslint.json new file mode 100644 index 0000000000..8f312f8fa9 --- /dev/null +++ b/types/happypack/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": ["tslint:recommended", "tslint-config-prettier"] +} + \ No newline at end of file From 308ec150ad5dcf3d2425e3bb7bb5477ffee1c7a8 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Tue, 15 Jan 2019 10:02:49 +0100 Subject: [PATCH 158/312] [node] add zlib.bytesWritten --- types/node/index.d.ts | 2 ++ types/node/node-tests.ts | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 417782b2f3..ffa98c32fb 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1781,7 +1781,9 @@ declare module "zlib" { } interface Zlib { + /** @deprecated Use bytesWritten instead. */ readonly bytesRead: number; + readonly bytesWritten: number; close(callback?: () => void): void; flush(kind?: number | (() => void), callback?: () => void): void; } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index f351ba8139..3a8622802a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -4172,6 +4172,11 @@ import * as constants from 'constants'; const deflate = zlib.deflateSync('test'); const inflate = zlib.inflateSync(deflate.toString()); } + + { + const gzip = zlib.createGzip(); + const written: number = gzip.bytesWritten; + } } /////////////////////////////////////////////////////////// From fb63f59f6b6364cb7d7861e4b022bb2c120e69fc Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Tue, 29 Jan 2019 08:16:59 +0100 Subject: [PATCH 159/312] getSells --- types/coinbase/coinbase-tests.ts | 2 +- types/coinbase/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts index e7d53012d7..65ec9693bd 100644 --- a/types/coinbase/coinbase-tests.ts +++ b/types/coinbase/coinbase-tests.ts @@ -33,7 +33,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined); - account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined); + account.getSells(null, (error: Error, deposit: coinbase.Sell[]): void => undefined); account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 4580179195..1e94f04295 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -678,7 +678,7 @@ export class Account implements Resource { * Lists sells for an account. * Scope: wallet:sells:read */ - getSells(cb: (error: Error, result: Sell[]) => void): void; + getSells(opts: null, cb: (error: Error, result: Sell[]) => void): void; /** * Show an individual sell. From f4408e85cb68e363135080a9ca8fb231e35175d4 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Tue, 29 Jan 2019 13:21:42 +0530 Subject: [PATCH 160/312] updating configuration --- types/happypack/tsconfig.json | 9 ++-- types/happypack/tslint.json | 79 ++++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 6 deletions(-) diff --git a/types/happypack/tsconfig.json b/types/happypack/tsconfig.json index b65889af68..82e6284376 100644 --- a/types/happypack/tsconfig.json +++ b/types/happypack/tsconfig.json @@ -2,11 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, + "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -17,6 +18,6 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", + "index.d.ts" ] -} +} \ No newline at end of file diff --git a/types/happypack/tslint.json b/types/happypack/tslint.json index 8f312f8fa9..a41bf5d19a 100644 --- a/types/happypack/tslint.json +++ b/types/happypack/tslint.json @@ -1,4 +1,79 @@ { - "extends": ["tslint:recommended", "tslint-config-prettier"] + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } } - \ No newline at end of file From c37c0288cc72c5c611c7fd29a507f781e6a4ed73 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Tue, 29 Jan 2019 13:32:53 +0530 Subject: [PATCH 161/312] Update index.d.ts --- types/happypack/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/happypack/index.d.ts b/types/happypack/index.d.ts index c42bdc1cf7..e1f6a8947e 100644 --- a/types/happypack/index.d.ts +++ b/types/happypack/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/amireh/happypack // Definitions by: Akash Vishwakarma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 import { Plugin } from 'webpack'; From 11a7577404c497b77781b4564dc8617a06e2803b Mon Sep 17 00:00:00 2001 From: Erik Zivkovic Date: Tue, 29 Jan 2019 11:31:17 +0100 Subject: [PATCH 162/312] Typo: Bootstrap v3 should say Bootstrap v4 --- types/react-bootstrap/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-bootstrap/README.md b/types/react-bootstrap/README.md index 114130171d..ec1bfc027f 100644 --- a/types/react-bootstrap/README.md +++ b/types/react-bootstrap/README.md @@ -7,7 +7,7 @@ The reason is that react-bootstrap `v1.0.0` targets Bootstrap v4, and includes i typings. react-bootstrap prior to `v1.0.0` targets Bootstrap v3 and does not include any typings. -It does not make sense for everyone to upgrade to Bootstrap v3, therefore these typings +It does not make sense for everyone to upgrade to Bootstrap v4, therefore these typings are useful for everyone that wants to stay on Bootstrap v3 and react-bootstrap prior to `v1.0.0`. The typings for `v1.0.0` were merged in [this pull request](https://github.com/react-bootstrap/react-bootstrap/commit/2079b2292afb835d036fcceef47e8938c4a8d86a). From e891129be1adea5d0869b10accf844f3fda05f58 Mon Sep 17 00:00:00 2001 From: use-strict Date: Tue, 29 Jan 2019 11:47:44 +0100 Subject: [PATCH 163/312] Update types/webpack-env/index.d.ts Co-Authored-By: luuksommers --- types/webpack-env/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webpack-env/index.d.ts b/types/webpack-env/index.d.ts index 0fde1243f4..293f06797d 100644 --- a/types/webpack-env/index.d.ts +++ b/types/webpack-env/index.d.ts @@ -32,7 +32,7 @@ declare namespace __WebpackModuleApi { * This creates a chunk. The chunk can be named. If a chunk with this name already exists, the dependencies are merged into that chunk and that chunk is used. */ ensure(paths: string[], callback: (require: NodeRequire) => void, errorCallback?: (error: any) => void, chunkName?: string): void; - context(path: string, deep?: boolean, filter?: RegExp, mode?: string): RequireContext; + context(path: string, deep?: boolean, filter?: RegExp, mode?: "sync" | "eager" | "weak" | "lazy" | "lazy-once"): RequireContext; /** * Returns the module id of a dependency. The call is sync. No request to the server is fired. The compiler ensures that the dependency is available. * From 4a6613663a2c998ad226c1273aead879dbb692e4 Mon Sep 17 00:00:00 2001 From: Dan <32849715+ddangelo-shoprunner@users.noreply.github.com> Date: Tue, 29 Jan 2019 10:43:46 -0500 Subject: [PATCH 164/312] typo - AuthorizeOptions accessType --- types/auth0-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index f2cc95105c..4fcbb5df33 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -812,7 +812,7 @@ export interface AuthorizeOptions { login_hint?: string; prompt?: string; mode?: "login" | "signUp"; - acccessType?: string; + accessType?: string; approvalPrompt?: string; } From c1c961cde8057a68e9edff9665f1924f2d7496e9 Mon Sep 17 00:00:00 2001 From: Jeroen Claassens Date: Tue, 29 Jan 2019 16:55:47 +0100 Subject: [PATCH 165/312] Add type definitions for mui-datatables Signed-off-by: Jeroen Claassens --- types/mui-datatables/index.d.ts | 173 ++++++++++++++++++ types/mui-datatables/mui-datatables-tests.tsx | 83 +++++++++ types/mui-datatables/tsconfig.json | 25 +++ types/mui-datatables/tslint.json | 1 + 4 files changed, 282 insertions(+) create mode 100644 types/mui-datatables/index.d.ts create mode 100644 types/mui-datatables/mui-datatables-tests.tsx create mode 100644 types/mui-datatables/tsconfig.json create mode 100644 types/mui-datatables/tslint.json diff --git a/types/mui-datatables/index.d.ts b/types/mui-datatables/index.d.ts new file mode 100644 index 0000000000..8a65c257c1 --- /dev/null +++ b/types/mui-datatables/index.d.ts @@ -0,0 +1,173 @@ +// Type definitions for mui-datatables 2.0 +// Project: https://github.com/gregnb/mui-datatable +// Definitions by: Jeroen "Favna" Claassens +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface MUIDataTableData { + index: number; + data: any[]; +} + +interface MUIDataTableStateRows { + data: string[]; + lookup: any; +} + +interface MUIDataTableState { + announceText: string | null; + activeColumn: string | null; + page: number; + rowsPerPage: number; + filterList: string[][]; + selectedRows: MUIDataTableStateRows; + expandedRows: MUIDataTableStateRows; + showResponsive: boolean; + searchText: string | null; + rowsPerPageOptions: number[]; +} + +interface MUIDataTableMeta { + rowIndex: number; + columnIndex: number; + columnData: MUIDataTableColumnOptions[]; + rowData: any[]; + tableData: MUIDataTableData[]; + tableState: MUIDataTableState; +} + +interface MUIDataTableCustomHeadRenderer extends MUIDataTableColumn { + index: number; +} + +interface MUIDataTableColumn { + name: string; + options?: MUIDataTableColumnOptions; +} + +interface MUIDataTableTextLabelsBody { + noMatch: string; + toolTip: string; +} + +interface MUIDataTableTextLabelsPagination { + next: string; + previous: string; + rowsPerPage: string; + displayRows: string; +} + +interface MUIDataTableTextLabelsToolbar { + search: string; + downloadCsv: string; + print: string; + viewColumns: string; + filterTable: string; +} + +interface MUIDataTableTextLabelsFilter { + all: string; + title: string; + reset: string; +} + +interface MUIDataTableTextLabelsViewColumns { + title: string; + titleAria: string; +} + +interface MUIDataTableTextLabelsSelectedRows { + text: string; + delete: string; + deleteAria: string; +} + +interface MUIDataTableTextLabels { + body: MUIDataTableTextLabelsBody; + pagination: MUIDataTableTextLabelsPagination; + toolbar: MUIDataTableTextLabelsToolbar; + filter: MUIDataTableTextLabelsFilter; + viewColumns: MUIDataTableTextLabelsViewColumns; + selectedRows: MUIDataTableTextLabelsSelectedRows; +} + +export interface MUIDataTableColumnOptions { + display?: 'true' | 'false' | 'excluded'; + filter?: boolean; + filterList?: string[]; + filterOptions?: string[]; + sort?: boolean; + sortDirection?: 'asc' | 'desc'; + download?: boolean; + hint?: string; + customHeadRender?: (columnMeta: MUIDataTableCustomHeadRenderer, updateDirection: (params: any) => any) => string; + customBodyRender?: (value: any, tableMeta: MUIDataTableMeta, updateValue: (s: any, c: any, p: any) => any) => string | React.ReactNode; + setCellProps?: (cellValue: string, rowIndex: number, columnIndex: number) => string; +} + +export interface MUIDataTableOptions { + page?: number; + count?: number; + serverSide?: boolean; + rowsSelected?: any[]; + filterType?: 'dropdown' | 'checkbox' | 'multiselect' | 'textField'; + textLabels?: MUIDataTableTextLabels; + pagination?: boolean; + selectableRows?: boolean; + IsRowSelectable?: (dataIndex: any) => boolean; + resizableColumns?: boolean; + expandableRows?: boolean; + renderExpandableRow?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => React.ReactNode; + customToolbar?: () => React.ReactNode; + customToolbarSelect?: () => React.ReactNode; + customFooter?: () => React.ReactNode; + customSort?: (data: any[], colIndex: number, order: string) => any[]; + elevation?: number; + caseSensitive?: boolean; + responsive?: 'stacked' | 'scroll'; + rowsPerPage?: number; + rowsPerPageOptions?: number[]; + rowHover?: boolean; + fixedHeader?: boolean; + sortFilterList?: boolean; + sort?: boolean; + filter?: boolean; + search?: boolean; + print?: boolean; + download?: boolean; + downloadOptions?: { filename: string; separator: string }; + viewColumns?: boolean; + onRowsSelect?: (currentRowsSelected: any[], rowsSelected: any[]) => void; + onRowsDelete?: (rowsDeleted: any[]) => void; + onRowClick?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => void; + onCellClick?: (colIndex: number, rowIndex: number) => void; + onChangePage?: (currentPage: number) => void; + onChangeRowsPerPage?: (numberOfRows: number) => void; + onSearchChange?: (searchText: string) => void; + onFilterChange?: (changedColumn: string, filterList: any[]) => void; + onColumnSortChange?: (changedColumn: string, direction: string) => void; + onColumnViewChange?: (changedColumn: string, action: string) => void; + onTableChange?: (action: string, tableState: object) => void; + setRowProps?: (row: any[], rowIndex: number) => any; +} + +export type MUIDataTableColumnDef = string | MUIDataTableColumn; + +export interface MuiDatatablesTableState { + page: number; + rowsPerPage: number; + filterList: any[]; +} + +export interface MUIDataTableProps { + title: string; + columns: MUIDataTableColumnDef[]; + data: any[]; + options?: MUIDataTableOptions; +} + +export const MUIDataTable: React.ComponentType; + +export default MUIDataTable; diff --git a/types/mui-datatables/mui-datatables-tests.tsx b/types/mui-datatables/mui-datatables-tests.tsx new file mode 100644 index 0000000000..5ad018082e --- /dev/null +++ b/types/mui-datatables/mui-datatables-tests.tsx @@ -0,0 +1,83 @@ +import MUIDataTable, { MUIDataTableColumnDef, MUIDataTableOptions } from 'mui-datatables'; +import * as React from 'react'; + +const dataSimple: string[][] = [ + ['Joe James', 'Test Corp', 'Yonkers', 'NY'], + ['John Walsh', 'Test Corp', 'Hartford', 'CT'], + ['Bob Herm', 'Test Corp', 'Tampa', 'FL'], + ['James Houston', 'Test Corp', 'Dallas', 'TX'] +]; + +const columnWithOptions: MUIDataTableColumnDef[] = [ + { + name: 'Name', + options: { + display: 'true', + filter: true, + sort: true, + sortDirection: 'asc', + download: true, + } + } +]; + +const options: MUIDataTableOptions = { + filterType: 'checkbox', + responsive: 'scroll', + selectableRows: false, + elevation: 0, + rowsPerPageOptions: [5, 10, 20, 25, 50, 100], + downloadOptions: { + filename: 'filename.csv', + separator: ',' + }, + sortFilterList: false, + textLabels: { + body: { + noMatch: 'Sorry, no matching records found', + toolTip: 'Sort', + }, + pagination: { + next: 'Next Page', + previous: 'Previous Page', + rowsPerPage: 'Rows per page:', + displayRows: 'of', + }, + toolbar: { + search: 'Search', + downloadCsv: 'Download CSV', + print: 'Print', + viewColumns: 'View Columns', + filterTable: 'Filter Table', + }, + filter: { + all: 'All', + title: 'FILTERS', + reset: 'RESET', + }, + viewColumns: { + title: 'Show Columns', + titleAria: 'Show/Hide Table Columns', + }, + selectedRows: { + text: 'rows(s) selected', + delete: 'Delete', + deleteAria: 'Delete Selected Rows', + } + } +}; + +class MuiDataTable extends React.Component { + render() { + return ( + + ); + } +} + +; diff --git a/types/mui-datatables/tsconfig.json b/types/mui-datatables/tsconfig.json new file mode 100644 index 0000000000..280efbb284 --- /dev/null +++ b/types/mui-datatables/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mui-datatables-tests.tsx" + ] +} diff --git a/types/mui-datatables/tslint.json b/types/mui-datatables/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mui-datatables/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From eb0e2a8404e869132825fe3b1661e62dd440647a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 29 Jan 2019 08:31:18 -0800 Subject: [PATCH 166/312] Update README to make typesVersions optional --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4343577bd0..7508fbc15f 100644 --- a/README.md +++ b/README.md @@ -268,8 +268,9 @@ Then you will have to add a comment to the last line of your definition header ( #### I want to use features from TypeScript 3.1 or above. -You will need to use the `typesVersions` feature of TypeScript 3.1 and above. You can find a detailed explanation -of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions). +You can use the same `// TypeScript Version: 3.1` comment as above. +However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above. +You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions). Here's a short explanation to get you started: From cc36a18fdac7c0b4d672cd83b15b81c8452f6fc6 Mon Sep 17 00:00:00 2001 From: nlaitine Date: Tue, 29 Jan 2019 18:57:35 +0200 Subject: [PATCH 167/312] Added formats and fixed registerFormat --- types/theo/index.d.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/types/theo/index.d.ts b/types/theo/index.d.ts index f1aacfe038..271cfce8ed 100644 --- a/types/theo/index.d.ts +++ b/types/theo/index.d.ts @@ -27,7 +27,12 @@ export type Format = | "list.scss" | "module.js" | "common.js" - | "html"; + | "html" + | "json" + | "raw.json" + | "ios.json" + | "android.xml" + | "aura.tokens"; export type Transform = "raw" | "ios" | "android" | "web"; @@ -43,7 +48,7 @@ export type ValueTransform = export function convert(options: ConvertOptions): Promise; export function convertSync(options: ConvertOptions): string; export function registerFormat( - name: Format, + name: string, format: FormatResultFn | string ): void; export function registerTransform( @@ -77,6 +82,8 @@ export interface ImmutableStyleMap extends Map { export interface ConvertOptions { transform: TransformOptions; format: FormatOptions; + resolveAliases?: boolean; + resolveMetaAliases?: boolean; } export interface TransformOptions { From b84616f46c08b84855eecdf75cb8d9e0b3fac966 Mon Sep 17 00:00:00 2001 From: nlaitine Date: Tue, 29 Jan 2019 19:01:04 +0200 Subject: [PATCH 168/312] Upgraded immutable npm package --- types/theo/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/theo/package.json b/types/theo/package.json index 12231bb461..6c119dd781 100644 --- a/types/theo/package.json +++ b/types/theo/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "immutable": "^3.8.2" + "immutable": "4.0.0-rc.12" } } From b54b861785a2cc51529525a641d96afb9f30766d Mon Sep 17 00:00:00 2001 From: nlaitine Date: Tue, 29 Jan 2019 19:34:14 +0200 Subject: [PATCH 169/312] Tests updated --- types/theo/index.d.ts | 7 ++++--- types/theo/theo-tests.ts | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/types/theo/index.d.ts b/types/theo/index.d.ts index 271cfce8ed..870123fadc 100644 --- a/types/theo/index.d.ts +++ b/types/theo/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for theo 8.0 +// Type definitions for theo 8.1.1 // Project: https://github.com/salesforce-ux/theo // Definitions by: Pete Petrash +// Niko Laitinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 3.2.4 -import { Iterable, Collection, Map, List, OrderedMap } from "immutable"; +import { Collection, Map, List, OrderedMap } from "immutable"; export type StyleProperty = | "name" diff --git a/types/theo/theo-tests.ts b/types/theo/theo-tests.ts index ceaaf9649c..154817793f 100644 --- a/types/theo/theo-tests.ts +++ b/types/theo/theo-tests.ts @@ -24,6 +24,7 @@ theo.registerValueTransform( "relative/pixelValue", prop => prop.get("category") === "sizing", prop => { + // @ts-ignore: prop can be undefined const value = prop.get("value").toString(); return parseFloat(value.replace(/rem/g, "")) * 16; } From 9db4cf5acae5ee1076b49f8442b4a013e2592b00 Mon Sep 17 00:00:00 2001 From: Florian Blischke Date: Tue, 29 Jan 2019 18:35:52 +0100 Subject: [PATCH 170/312] fixed version --- types/jquery.soap/index.d.ts | 2 +- types/jquery.soap/tslint.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/jquery.soap/index.d.ts b/types/jquery.soap/index.d.ts index f511d05575..9a802163e4 100644 --- a/types/jquery.soap/index.d.ts +++ b/types/jquery.soap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery.SOAP 1.7.3 +// Type definitions for jQuery.SOAP 1.7 // Project: https://github.com/doedje/jquery.soap // Definitions by: Roland Greim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ diff --git a/types/jquery.soap/tslint.json b/types/jquery.soap/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/jquery.soap/tslint.json +++ b/types/jquery.soap/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, From a61dfc49583ce7e1b8b3352e172cdb6bb5c92eef Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Tue, 29 Jan 2019 15:31:08 -0300 Subject: [PATCH 171/312] [trezor-connect] Fix Output types --- types/trezor-connect/index.d.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index c9c5fb258d..282117efda 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -249,7 +249,13 @@ export interface Input { export interface RegularOutput { address: string; amount: string; - script_type: string; + script_type?: string; +} + +export interface InternalOutput { + address_n: number[]; + amount: string; + script_type?: string; } export interface SendMaxOutput { @@ -262,7 +268,7 @@ export interface OpReturnOutput { dataHex: string; } -export type Output = RegularOutput | SendMaxOutput | OpReturnOutput; +export type Output = RegularOutput | InternalOutput | SendMaxOutput | OpReturnOutput; export interface SignTransactionParams extends CommonParams { inputs: Input[]; From f4614d3afbf18b376f25c356931dd009a3a607ea Mon Sep 17 00:00:00 2001 From: licui Date: Tue, 29 Jan 2019 13:48:52 -0500 Subject: [PATCH 172/312] Create v37 folder --- .../v37/_v2/api/application/application.d.ts | 242 +++ .../api/application/applicationOption.d.ts | 50 + types/openfin/v37/_v2/api/base.d.ts | 46 + .../v37/_v2/api/clipboard/clipboard.d.ts | 70 + .../v37/_v2/api/clipboard/write-request.d.ts | 12 + .../v37/_v2/api/events/application.d.ts | 56 + types/openfin/v37/_v2/api/events/base.d.ts | 18 + types/openfin/v37/_v2/api/events/channel.d.ts | 10 + .../v37/_v2/api/events/emitterMap.d.ts | 15 + .../v37/_v2/api/events/eventAggregator.d.ts | 5 + .../_v2/api/events/externalApplication.d.ts | 5 + types/openfin/v37/_v2/api/events/frame.d.ts | 9 + .../v37/_v2/api/events/globalHotkey.d.ts | 11 + .../v37/_v2/api/events/notifications.d.ts | 8 + types/openfin/v37/_v2/api/events/system.d.ts | 22 + types/openfin/v37/_v2/api/events/window.d.ts | 176 +++ .../external-application.d.ts | 44 + types/openfin/v37/_v2/api/fin.d.ts | 27 + types/openfin/v37/_v2/api/frame/frame.d.ts | 69 + .../v37/_v2/api/global-hotkey/index.d.ts | 38 + .../_v2/api/interappbus/channel/channel.d.ts | 31 + .../_v2/api/interappbus/channel/client.d.ts | 6 + .../_v2/api/interappbus/channel/index.d.ts | 32 + .../_v2/api/interappbus/channel/provider.d.ts | 15 + .../v37/_v2/api/interappbus/interappbus.d.ts | 80 + .../_v2/api/notification/notification.d.ts | 70 + .../v37/_v2/api/system/application.d.ts | 5 + .../v37/_v2/api/system/clearCacheOption.d.ts | 6 + types/openfin/v37/_v2/api/system/cookie.d.ts | 8 + .../_v2/api/system/crashReporterOption.d.ts | 4 + .../v37/_v2/api/system/download-asset.d.ts | 18 + .../v37/_v2/api/system/download-preload.d.ts | 8 + types/openfin/v37/_v2/api/system/entity.d.ts | 11 + .../v37/_v2/api/system/external-process.d.ts | 36 + .../v37/_v2/api/system/host-specs.d.ts | 24 + types/openfin/v37/_v2/api/system/log.d.ts | 11 + types/openfin/v37/_v2/api/system/monitor.d.ts | 39 + types/openfin/v37/_v2/api/system/point.d.ts | 8 + types/openfin/v37/_v2/api/system/process.d.ts | 15 + types/openfin/v37/_v2/api/system/proxy.d.ts | 15 + .../v37/_v2/api/system/registry-info.d.ts | 7 + .../v37/_v2/api/system/runtime-info.d.ts | 7 + types/openfin/v37/_v2/api/system/rvm.d.ts | 8 + types/openfin/v37/_v2/api/system/system.d.ts | 588 ++++++++ types/openfin/v37/_v2/api/system/window.d.ts | 16 + .../v37/_v2/api/window/anchor-type.d.ts | 1 + .../v37/_v2/api/window/bounds-changed.d.ts | 14 + types/openfin/v37/_v2/api/window/bounds.d.ts | 9 + .../v37/_v2/api/window/transition.d.ts | 24 + types/openfin/v37/_v2/api/window/window.d.ts | 778 ++++++++++ .../v37/_v2/api/window/windowOption.d.ts | 46 + .../v37/_v2/environment/environment.d.ts | 10 + .../openfin/v37/_v2/environment/node-env.d.ts | 11 + .../v37/_v2/environment/openfin-env.d.ts | 11 + .../_v2/environment/openfin-renderer-api.d.ts | 6 + types/openfin/v37/_v2/identity.d.ts | 4 + types/openfin/v37/_v2/launcher/launcher.d.ts | 15 + .../openfin/v37/_v2/launcher/nix-launch.d.ts | 14 + types/openfin/v37/_v2/launcher/util.d.ts | 8 + .../openfin/v37/_v2/launcher/win-launch.d.ts | 4 + types/openfin/v37/_v2/main.d.ts | 11 + types/openfin/v37/_v2/of-main.d.ts | 1 + types/openfin/v37/_v2/transport/elipc.d.ts | 13 + .../v37/_v2/transport/port-discovery.d.ts | 17 + .../v37/_v2/transport/transport-errors.d.ts | 17 + .../openfin/v37/_v2/transport/transport.d.ts | 65 + .../openfin/v37/_v2/transport/websocket.d.ts | 14 + types/openfin/v37/_v2/transport/wire.d.ts | 71 + .../v37/_v2/util/normalize-config.d.ts | 3 + types/openfin/v37/_v2/util/promises.d.ts | 5 + types/openfin/v37/_v2/util/ref-counter.d.ts | 7 + types/openfin/v37/index.d.ts | 1304 +++++++++++++++++ types/openfin/v37/openfin-tests.ts | 851 +++++++++++ types/openfin/v37/tsconfig.json | 84 ++ types/openfin/v37/tslint.json | 18 + 75 files changed, 5437 insertions(+) create mode 100644 types/openfin/v37/_v2/api/application/application.d.ts create mode 100644 types/openfin/v37/_v2/api/application/applicationOption.d.ts create mode 100644 types/openfin/v37/_v2/api/base.d.ts create mode 100644 types/openfin/v37/_v2/api/clipboard/clipboard.d.ts create mode 100644 types/openfin/v37/_v2/api/clipboard/write-request.d.ts create mode 100644 types/openfin/v37/_v2/api/events/application.d.ts create mode 100644 types/openfin/v37/_v2/api/events/base.d.ts create mode 100644 types/openfin/v37/_v2/api/events/channel.d.ts create mode 100644 types/openfin/v37/_v2/api/events/emitterMap.d.ts create mode 100644 types/openfin/v37/_v2/api/events/eventAggregator.d.ts create mode 100644 types/openfin/v37/_v2/api/events/externalApplication.d.ts create mode 100644 types/openfin/v37/_v2/api/events/frame.d.ts create mode 100644 types/openfin/v37/_v2/api/events/globalHotkey.d.ts create mode 100644 types/openfin/v37/_v2/api/events/notifications.d.ts create mode 100644 types/openfin/v37/_v2/api/events/system.d.ts create mode 100644 types/openfin/v37/_v2/api/events/window.d.ts create mode 100644 types/openfin/v37/_v2/api/external-application/external-application.d.ts create mode 100644 types/openfin/v37/_v2/api/fin.d.ts create mode 100644 types/openfin/v37/_v2/api/frame/frame.d.ts create mode 100644 types/openfin/v37/_v2/api/global-hotkey/index.d.ts create mode 100644 types/openfin/v37/_v2/api/interappbus/channel/channel.d.ts create mode 100644 types/openfin/v37/_v2/api/interappbus/channel/client.d.ts create mode 100644 types/openfin/v37/_v2/api/interappbus/channel/index.d.ts create mode 100644 types/openfin/v37/_v2/api/interappbus/channel/provider.d.ts create mode 100644 types/openfin/v37/_v2/api/interappbus/interappbus.d.ts create mode 100644 types/openfin/v37/_v2/api/notification/notification.d.ts create mode 100644 types/openfin/v37/_v2/api/system/application.d.ts create mode 100644 types/openfin/v37/_v2/api/system/clearCacheOption.d.ts create mode 100644 types/openfin/v37/_v2/api/system/cookie.d.ts create mode 100644 types/openfin/v37/_v2/api/system/crashReporterOption.d.ts create mode 100644 types/openfin/v37/_v2/api/system/download-asset.d.ts create mode 100644 types/openfin/v37/_v2/api/system/download-preload.d.ts create mode 100644 types/openfin/v37/_v2/api/system/entity.d.ts create mode 100644 types/openfin/v37/_v2/api/system/external-process.d.ts create mode 100644 types/openfin/v37/_v2/api/system/host-specs.d.ts create mode 100644 types/openfin/v37/_v2/api/system/log.d.ts create mode 100644 types/openfin/v37/_v2/api/system/monitor.d.ts create mode 100644 types/openfin/v37/_v2/api/system/point.d.ts create mode 100644 types/openfin/v37/_v2/api/system/process.d.ts create mode 100644 types/openfin/v37/_v2/api/system/proxy.d.ts create mode 100644 types/openfin/v37/_v2/api/system/registry-info.d.ts create mode 100644 types/openfin/v37/_v2/api/system/runtime-info.d.ts create mode 100644 types/openfin/v37/_v2/api/system/rvm.d.ts create mode 100644 types/openfin/v37/_v2/api/system/system.d.ts create mode 100644 types/openfin/v37/_v2/api/system/window.d.ts create mode 100644 types/openfin/v37/_v2/api/window/anchor-type.d.ts create mode 100644 types/openfin/v37/_v2/api/window/bounds-changed.d.ts create mode 100644 types/openfin/v37/_v2/api/window/bounds.d.ts create mode 100644 types/openfin/v37/_v2/api/window/transition.d.ts create mode 100644 types/openfin/v37/_v2/api/window/window.d.ts create mode 100644 types/openfin/v37/_v2/api/window/windowOption.d.ts create mode 100644 types/openfin/v37/_v2/environment/environment.d.ts create mode 100644 types/openfin/v37/_v2/environment/node-env.d.ts create mode 100644 types/openfin/v37/_v2/environment/openfin-env.d.ts create mode 100644 types/openfin/v37/_v2/environment/openfin-renderer-api.d.ts create mode 100644 types/openfin/v37/_v2/identity.d.ts create mode 100644 types/openfin/v37/_v2/launcher/launcher.d.ts create mode 100644 types/openfin/v37/_v2/launcher/nix-launch.d.ts create mode 100644 types/openfin/v37/_v2/launcher/util.d.ts create mode 100644 types/openfin/v37/_v2/launcher/win-launch.d.ts create mode 100644 types/openfin/v37/_v2/main.d.ts create mode 100644 types/openfin/v37/_v2/of-main.d.ts create mode 100644 types/openfin/v37/_v2/transport/elipc.d.ts create mode 100644 types/openfin/v37/_v2/transport/port-discovery.d.ts create mode 100644 types/openfin/v37/_v2/transport/transport-errors.d.ts create mode 100644 types/openfin/v37/_v2/transport/transport.d.ts create mode 100644 types/openfin/v37/_v2/transport/websocket.d.ts create mode 100644 types/openfin/v37/_v2/transport/wire.d.ts create mode 100644 types/openfin/v37/_v2/util/normalize-config.d.ts create mode 100644 types/openfin/v37/_v2/util/promises.d.ts create mode 100644 types/openfin/v37/_v2/util/ref-counter.d.ts create mode 100644 types/openfin/v37/index.d.ts create mode 100644 types/openfin/v37/openfin-tests.ts create mode 100644 types/openfin/v37/tsconfig.json create mode 100644 types/openfin/v37/tslint.json diff --git a/types/openfin/v37/_v2/api/application/application.d.ts b/types/openfin/v37/_v2/api/application/application.d.ts new file mode 100644 index 0000000000..37263a9a63 --- /dev/null +++ b/types/openfin/v37/_v2/api/application/application.d.ts @@ -0,0 +1,242 @@ +import { EmitterBase, Base, Reply } from '../base'; +import { Identity } from '../../identity'; +import { _Window } from '../window/window'; +import { Point } from '../system/point'; +import { MonitorInfo } from '../system/monitor'; +import Transport from '../../transport/transport'; +import Bounds from '../window/bounds'; +import { ApplicationEvents } from '../events/application'; +import { ApplicationOption } from './applicationOption'; +export interface TrayIconClickReply extends Point, Reply<'application', 'tray-icon-clicked'> { + button: number; + monitorInfo: MonitorInfo; +} +export interface ApplicationInfo { + initialOptions: object; + launchMode: string; + manifest: object; + manifestUrl: string; + parentUuid?: string; + runtime: object; +} +export declare class NavigationRejectedReply extends Reply<'window-navigation-rejected', void> { + sourceName: string; + url: string; +} +export interface ShortCutConfig { + desktop?: boolean; + startMenu?: boolean; + systemStartup?: boolean; +} +export interface TrayInfo { + bounds: Bounds; + monitorInfo: MonitorInfo; + x: number; + y: number; +} +/** + * @lends Application + */ +export default class ApplicationModule extends Base { + /** + * Asynchronously returns an Application object that represents an existing application. + * @param { Identity } identity + * @return {Promise.} + * @tutorial Application.wrap + * @static + */ + wrap(identity: Identity): Promise; + /** + * Synchronously returns an Application object that represents an existing application. + * @param { Identity } identity + * @return {Application} + * @tutorial Application.wrapSync + * @static + */ + wrapSync(identity: Identity): Application; + /** + * Creates a new Application. + * @param { ApplicationOption } appOptions + * @return {Promise.} + * @tutorial Application.create + * @static + */ + create(appOptions: ApplicationOption): Promise; + /** + * Asynchronously returns an Application object that represents the current application + * @return {Promise.} + * @tutorial Application.getCurrent + * @static + */ + getCurrent(): Promise; + /** + * Synchronously returns an Application object that represents the current application + * @return {Application} + * @tutorial Application.getCurrentSync + * @static + */ + getCurrentSync(): Application; + /** + * Retrieves application's manifest and returns a wrapped application. + * @param {string} manifestUrl - The URL of app's manifest. + * @return {Promise.} + * @tutorial Application.createFromManifest + * @static + */ + createFromManifest(manifestUrl: string): Promise; +} +/** + * @classdesc An object representing an application. Allows the developer to create, + * execute, show/close an application as well as listen to application events. + * @class + */ +export declare class Application extends EmitterBase { + identity: Identity; + _manifestUrl?: string; + private window; + constructor(wire: Transport, identity: Identity); + private windowListFromIdentityList; + /** + * Determines if the application is currently running. + * @return {Promise.} + * @tutorial Application.isRunning + */ + isRunning(): Promise; + /** + * Closes the application and any child windows created by the application. + * @param { boolean } [force = false] Close will be prevented from closing when force is false and + * ‘close-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Application.close + */ + close(force?: boolean): Promise; + /** + * Retrieves an array of wrapped fin.Windows for each of the application’s child windows. + * @return {Promise.Array.<_Window>} + * @tutorial Application.getChildWindows + */ + getChildWindows(): Promise>; + /** + * Retrieves an array of active window groups for all of the application's windows. Each group is + * represented as an array of wrapped fin.Windows. + * @return {Promise.Array.Array.<_Window>} + * @tutorial Application.getGroups + */ + getGroups(): Promise>>; + /** + * Retrieves the JSON manifest that was used to create the application. Invokes the error callback + * if the application was not created from a manifest. + * @return {Promise.} + * @tutorial Application.getManifest + */ + getManifest(): Promise; + /** + * Retrieves UUID of the application that launches this application. Invokes the error callback + * if the application was created from a manifest. + * @return {Promise.} + * @tutorial Application.getParentUuid + */ + getParentUuid(): Promise; + /** + * Retrieves current application's shortcut configuration. + * @return {Promise.} + * @tutorial Application.getShortcuts + */ + getShortcuts(): Promise; + /** + * Returns the current zoom level of the application. + * @return {Promise.} + * @tutorial Application.getZoomLevel + */ + getZoomLevel(): Promise; + /** + * Returns an instance of the main Window of the application + * @return {Promise.<_Window>} + * @tutorial Application.getWindow + */ + getWindow(): Promise<_Window>; + /** + * Manually registers a user with the licensing service. The only data sent by this call is userName and appName. + * @param { string } userName - username to be passed to the RVM. + * @param { string } appName - app name to be passed to the RVM. + * @return {Promise.} + * @tutorial Application.registerUser + */ + registerUser(userName: string, appName: string): Promise; + /** + * Removes the application’s icon from the tray. + * @return {Promise.} + * @tutorial Application.removeTrayIcon + */ + removeTrayIcon(): Promise; + /** + * Restarts the application. + * @return {Promise.} + * @tutorial Application.restart + */ + restart(): Promise; + /** + * Runs the application. When the application is created, run must be called. + * @return {Promise.} + * @tutorial Application.run + */ + run(): Promise; + /** + * Instructs the RVM to schedule one restart of the application. + * @return {Promise.} + * @tutorial Application.scheduleRestart + */ + scheduleRestart(): Promise; + /** + * Adds a customizable icon in the system tray and notifies the application when clicked. + * @param { string } iconUrl Image URL to be used as the icon + * @return {Promise.} + * @tutorial Application.setTrayIcon + */ + setTrayIcon(iconUrl: string): Promise; + /** + * Sets new application's shortcut configuration. + * @param { Object } config New application's shortcut configuration. + * @param {Boolean} [config.desktop] - Enable/disable desktop shortcut. + * @param {Boolean} [config.startMenu] - Enable/disable start menu shortcut. + * @param {Boolean} [config.systemStartup] - Enable/disable system startup shortcut. + * @return {Promise.} + * @tutorial Application.setShortcuts + */ + setShortcuts(config: ShortCutConfig): Promise; + /** + * Sets the zoom level of the application. The original size is 0 and each increment above or below represents zooming 20% + * larger or smaller to default limits of 300% and 50% of original size, respectively. + * @param { number } level The zoom level + * @return {Promise.} + * @tutorial Application.setZoomLevel + */ + setZoomLevel(level: number): Promise; + /** + * @summary Retrieves information about the system tray. + * @desc The only information currently returned is the position and dimensions. + * @return {Promise.} + * @tutorial Application.getTrayIconInfo + */ + getTrayIconInfo(): Promise; + /** + * Closes the application by terminating its process. + * @return {Promise.} + * @tutorial Application.terminate + */ + terminate(): Promise; + /** + * Waits for a hanging application. This method can be called in response to an application + * "not-responding" to allow the application to continue and to generate another "not-responding" + * message after a certain period of time. + * @return {Promise.} + * @ignore + */ + wait(): Promise; + /** + * Retrieves information about the application. + * @return {Promise.} + * @tutorial Application.getInfo + */ + getInfo(): Promise; +} diff --git a/types/openfin/v37/_v2/api/application/applicationOption.d.ts b/types/openfin/v37/_v2/api/application/applicationOption.d.ts new file mode 100644 index 0000000000..134e4482d6 --- /dev/null +++ b/types/openfin/v37/_v2/api/application/applicationOption.d.ts @@ -0,0 +1,50 @@ +import { WindowOption, CustomRequestHeaders } from '../window/windowOption'; +import { DownloadPreloadOption } from '../system/download-preload'; +export interface ApplicationOption { + disableIabSecureLogging?: boolean; + loadErrorMessage?: string; + mainWindowOptions?: WindowOption; + name?: string; + nonPersistent?: boolean; + plugins?: boolean; + spellCheck?: boolean; + url?: string; + uuid: string; + webSecurity?: boolean; + accelerator?: object; + alwaysOnTop?: boolean; + api?: object; + aspectRatio?: number; + autoShow?: boolean; + backgroundColor?: string; + contentNavigation?: object; + contextMenu?: boolean; + cornerRounding?: object; + customData?: string; + customRequestHeaders?: Array; + defaultCentered?: boolean; + defaultHeight?: number; + defaultLeft?: number; + defaultTop?: number; + defaultWidth?: number; + frame?: boolean; + hideOnClose?: boolean; + icon?: string; + maxHeight?: number; + maximizable?: boolean; + maxWidth?: number; + minHeight?: number; + minimizable?: boolean; + minWidth?: number; + opacity?: number; + preloadScripts?: Array; + resizable?: boolean; + resizeRegion?: object; + saveWindowState?: boolean; + shadow?: boolean; + showTaskbarIcon?: boolean; + smallWindow?: boolean; + state?: string; + taskbarIconGroup?: string; + waitForPageLoad?: boolean; +} diff --git a/types/openfin/v37/_v2/api/base.d.ts b/types/openfin/v37/_v2/api/base.d.ts new file mode 100644 index 0000000000..5cbb8658a7 --- /dev/null +++ b/types/openfin/v37/_v2/api/base.d.ts @@ -0,0 +1,46 @@ +/// +import Transport from '../transport/transport'; +import { Identity } from '../identity'; +import { EventEmitter } from 'events'; +import { EmitterAccessor } from './events/emitterMap'; +import { BaseEventMap } from './events/base'; +interface SubOptions { + timestamp?: number; +} +export declare class Base { + wire: Transport; + constructor(wire: Transport); + private _topic; + protected topic: string; + readonly me: Identity; + protected isNodeEnvironment: () => boolean; + protected isOpenFinEnvironment: () => boolean; +} +export declare class EmitterBase extends Base { + private emitterAccessor; + protected identity: Identity; + constructor(wire: Transport, emitterAccessor: EmitterAccessor); + eventNames: () => (string | symbol)[]; + emit: >(eventName: E, payload: E extends Extract ? EventTypes[E] : any, ...args: any[]) => boolean; + private hasEmitter; + private getEmitter; + listeners: (type: string | symbol) => Function[]; + listenerCount: (type: string | symbol) => number; + protected registerEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; + protected deregisterEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; + on | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + addListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; + once | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + prependListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + prependOnceListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + removeListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + protected deregisterAllListeners: (eventType: string | symbol | Extract) => Promise; + removeAllListeners(eventType?: Extract | string | symbol): Promise; +} +export declare class Reply implements Identity { + topic: TOPIC; + type: TYPE; + uuid: string; + name?: string; +} +export {}; diff --git a/types/openfin/v37/_v2/api/clipboard/clipboard.d.ts b/types/openfin/v37/_v2/api/clipboard/clipboard.d.ts new file mode 100644 index 0000000000..11b466dea0 --- /dev/null +++ b/types/openfin/v37/_v2/api/clipboard/clipboard.d.ts @@ -0,0 +1,70 @@ +import { Base } from '../base'; +import { WriteRequestType, WriteAnyRequestType } from './write-request'; +/** + * WriteRequestType interface + * @typedef { Object } WriteRequestType + * @property { string } name The name of the running application + * @property { string } uuid The uuid of the running application + */ +/** + * The Clipboard API allows reading and writing to the clipboard in multiple formats. + * @namespace +*/ +export default class Clipboard extends Base { + /** + * Writes data into the clipboard as plain text + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typeof + * @return {Promise.} + * @tutorial Clipboard.writeText + */ + writeText(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as plain text + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readText + */ + readText(type?: string): Promise; + /** + * Writes data into the clipboard as Html + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.writeHtml + */ + writeHtml(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as Html + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readHtml + */ + readHtml(type?: string): Promise; + /** + * Writes data into the clipboard as Rtf + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.writeRtf + */ + writeRtf(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as Rtf + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readRtf + */ + readRtf(type?: string): Promise; + /** + * Writes data into the clipboard + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.write + */ + write(writeObj: WriteAnyRequestType): Promise; + /** + * Reads available formats for the clipboard type + * @param { string } type Clipboard Type + * @return {Promise.Array.} + * @tutorial Clipboard.getAvailableFormats + */ + getAvailableFormats(type?: string): Promise>; +} diff --git a/types/openfin/v37/_v2/api/clipboard/write-request.d.ts b/types/openfin/v37/_v2/api/clipboard/write-request.d.ts new file mode 100644 index 0000000000..a2fc5c333e --- /dev/null +++ b/types/openfin/v37/_v2/api/clipboard/write-request.d.ts @@ -0,0 +1,12 @@ +export interface WriteRequestType { + data: string; + type?: string; +} +export interface WriteAnyRequestType { + data: { + text?: string; + html?: string; + rtf?: string; + }; + type?: string; +} diff --git a/types/openfin/v37/_v2/api/events/application.d.ts b/types/openfin/v37/_v2/api/events/application.d.ts new file mode 100644 index 0000000000..444d358cbd --- /dev/null +++ b/types/openfin/v37/_v2/api/events/application.d.ts @@ -0,0 +1,56 @@ +import { WindowEvent, BaseEventMap, ApplicationEvent } from './base'; +import { WindowAlertRequestedEvent, WindowAuthRequestedEvent, WindowEndLoadEvent, PropagatedWindowEvents } from './window'; +export interface CrashedEvent { + reason: 'normal-termination' | 'abnormal-termination' | 'killed' | 'crashed' | 'still-running' | 'launch-failed' | 'out-of-memory'; +} +export interface RunRequestedEvent extends ApplicationEvent { + userAppConfigArgs: any; +} +export interface TrayIconClicked extends ApplicationEvent { + button: 0 | 1 | 2; + x: number; + y: number; + monitorInfo: any; +} +export interface ApplicationEventMapping extends BaseEventMap { + 'closed': ApplicationEvent; + 'connected': ApplicationEvent; + 'crashed': CrashedEvent & ApplicationEvent; + 'initialized': ApplicationEvent; + 'manifest-changed': ApplicationEvent; + 'not-responding': ApplicationEvent; + 'responding': ApplicationEvent; + 'run-requested': RunRequestedEvent; + 'started': ApplicationEvent; + 'tray-icon-clicked': TrayIconClicked; + 'window-alert-requested': WindowAlertRequestedEvent; + 'window-auth-requested': WindowAuthRequestedEvent; + 'window-created': WindowEvent; + 'window-end-load': WindowEndLoadEvent; + 'window-not-responding': WindowEvent; + 'window-responding': WindowEvent; + 'window-show-requested': WindowEvent; + 'window-start-load': WindowEvent; +} +export interface PropagatedApplicationEventMapping { + 'application-closed': ApplicationEvent; + 'application-connected': ApplicationEvent; + 'application-crashed': CrashedEvent & ApplicationEvent; + 'application-initialized': ApplicationEvent; + 'application-manifest-changed': ApplicationEvent; + 'application-not-responding': ApplicationEvent; + 'application-responding': ApplicationEvent; + 'application-started': ApplicationEvent; + 'application-tray-icon-clicked': TrayIconClicked; + 'window-created': WindowEvent; + 'window-end-load': WindowEndLoadEvent; + 'window-not-responding': WindowEvent; + 'window-responding': WindowEvent; + 'window-start-load': WindowEvent; +} +export declare type ApplicationEvents = PropagatedWindowEvents<'application'> & { + [Type in keyof ApplicationEventMapping]: ApplicationEventMapping<'application', Type>[Type]; +}; +export declare type PropagatedApplicationEvents = { + [Type in keyof PropagatedApplicationEventMapping]: PropagatedApplicationEventMapping[Type]; +}; diff --git a/types/openfin/v37/_v2/api/events/base.d.ts b/types/openfin/v37/_v2/api/events/base.d.ts new file mode 100644 index 0000000000..700f82679b --- /dev/null +++ b/types/openfin/v37/_v2/api/events/base.d.ts @@ -0,0 +1,18 @@ +import { FrameEvent } from './frame'; +export declare type RuntimeEvent = Topic extends 'window' ? WindowEvent : Topic extends 'frame' ? FrameEvent : Topic extends 'application' ? ApplicationEvent : BaseEvent; +export interface BaseEvent { + topic: Topic; + type: Type; +} +export interface ApplicationEvent extends BaseEvent { + uuid: string; +} +export interface WindowEvent extends ApplicationEvent { + name: string; +} +export declare function getTopic(e: RuntimeEvent): string; +export interface BaseEventMap { + [name: string]: any; + 'newListener': string; + 'listenerRemoved': string; +} diff --git a/types/openfin/v37/_v2/api/events/channel.d.ts b/types/openfin/v37/_v2/api/events/channel.d.ts new file mode 100644 index 0000000000..3c448071cb --- /dev/null +++ b/types/openfin/v37/_v2/api/events/channel.d.ts @@ -0,0 +1,10 @@ +import { BaseEventMap, ApplicationEvent } from './base'; +export interface ChannelEvent extends ApplicationEvent<'channel', Type> { + channelName: string; + channelId: string; + name?: string; +} +export interface ChannelEvents extends BaseEventMap { + 'connected': ChannelEvent<'connected'>; + 'disconnected': ChannelEvent<'disconnected'>; +} diff --git a/types/openfin/v37/_v2/api/events/emitterMap.d.ts b/types/openfin/v37/_v2/api/events/emitterMap.d.ts new file mode 100644 index 0000000000..aa3fb498e8 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/emitterMap.d.ts @@ -0,0 +1,15 @@ +/// +import { EventEmitter } from 'events'; +export declare class EmitterMap { + private storage; + constructor(); + private hashKeys; + get(keys: EmitterAccessor): EventEmitter; + has(keys: EmitterAccessor): boolean; + delete(keys: EmitterAccessor): boolean; +} +export declare type SystemEmitterAccessor = ['system']; +export declare type ApplicationEmitterAccessor = ['application', string]; +export declare type WindowEmitterAccessor = ['window', string, string]; +export declare type HotkeyEmitterAccessor = ['global-hotkey']; +export declare type EmitterAccessor = SystemEmitterAccessor | ApplicationEmitterAccessor | WindowEmitterAccessor | HotkeyEmitterAccessor | string[]; diff --git a/types/openfin/v37/_v2/api/events/eventAggregator.d.ts b/types/openfin/v37/_v2/api/events/eventAggregator.d.ts new file mode 100644 index 0000000000..ac7b7ca1b2 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/eventAggregator.d.ts @@ -0,0 +1,5 @@ +import { Message } from '../../transport/transport'; +import { EmitterMap } from './emitterMap'; +export declare class EventAggregator extends EmitterMap { + dispatchEvent: (message: Message) => boolean; +} diff --git a/types/openfin/v37/_v2/api/events/externalApplication.d.ts b/types/openfin/v37/_v2/api/events/externalApplication.d.ts new file mode 100644 index 0000000000..f7cd85f45d --- /dev/null +++ b/types/openfin/v37/_v2/api/events/externalApplication.d.ts @@ -0,0 +1,5 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +export interface ExternalApplicationEvents extends BaseEventMap { + connected: RuntimeEvent<'externalapplication', 'connected'>; + disconnected: RuntimeEvent<'externalapplication', 'disconnected'>; +} diff --git a/types/openfin/v37/_v2/api/events/frame.d.ts b/types/openfin/v37/_v2/api/events/frame.d.ts new file mode 100644 index 0000000000..c31933e557 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/frame.d.ts @@ -0,0 +1,9 @@ +import { BaseEventMap, WindowEvent } from './base'; +export interface FrameEvent extends WindowEvent<'frame', Type> { + entityType: 'iframe'; + frameName: string; +} +export interface FrameEvents extends BaseEventMap { + connected: FrameEvent<'connected'>; + disconnected: FrameEvent<'disconnected'>; +} diff --git a/types/openfin/v37/_v2/api/events/globalHotkey.d.ts b/types/openfin/v37/_v2/api/events/globalHotkey.d.ts new file mode 100644 index 0000000000..561baba446 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/globalHotkey.d.ts @@ -0,0 +1,11 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +import { Identity } from '../../identity'; +import { nonHotkeyEvents } from '../global-hotkey'; +export interface GlobalHotkeyEvent extends RuntimeEvent<'global-hotkey', Type> { + identity: Identity; + hotkey: string; +} +export interface GlobalHotkeyEvents extends BaseEventMap { + [nonHotkeyEvents.REGISTERED]: GlobalHotkeyEvent; + [nonHotkeyEvents.UNREGISTERED]: GlobalHotkeyEvent; +} diff --git a/types/openfin/v37/_v2/api/events/notifications.d.ts b/types/openfin/v37/_v2/api/events/notifications.d.ts new file mode 100644 index 0000000000..a269817222 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/notifications.d.ts @@ -0,0 +1,8 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +export interface NotificationEvents extends BaseEventMap { + show: RuntimeEvent<'notification', 'show'>; + close: RuntimeEvent<'notification', 'close'>; + error: RuntimeEvent<'notification', 'error'>; + click: RuntimeEvent<'notification', 'click'>; + message: RuntimeEvent<'notification', 'message'>; +} diff --git a/types/openfin/v37/_v2/api/events/system.d.ts b/types/openfin/v37/_v2/api/events/system.d.ts new file mode 100644 index 0000000000..20285a8862 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/system.d.ts @@ -0,0 +1,22 @@ +import { BaseEvent, ApplicationEvent, BaseEventMap } from './base'; +import { MonitorInfo } from '../system/monitor'; +import { PropagatedWindowEvents } from './window'; +import { PropagatedApplicationEvents } from './application'; +export interface IdleEvent extends BaseEvent { + elapsedTime: number; + isIdle: boolean; +} +export declare type MonitorEvent = MonitorInfo & BaseEvent; +export interface SessionChangedEvent extends BaseEvent { + reason: 'lock' | 'unlock' | 'remote-connect' | 'remote-disconnect' | 'unknown'; +} +export interface SystemEventMapping extends BaseEventMap { + 'application-created': ApplicationEvent; + 'desktop-icon-clicked': ApplicationEvent; + 'idle-state-changed': IdleEvent; + 'monitor-info-changed': MonitorEvent; + 'session-changed': SessionChangedEvent; +} +export declare type SystemEvents = PropagatedWindowEvents<'system'> & PropagatedApplicationEvents<'system'> & { + [Type in keyof SystemEventMapping]: SystemEventMapping<'system', Type>[Type]; +}; diff --git a/types/openfin/v37/_v2/api/events/window.d.ts b/types/openfin/v37/_v2/api/events/window.d.ts new file mode 100644 index 0000000000..85d4d553f0 --- /dev/null +++ b/types/openfin/v37/_v2/api/events/window.d.ts @@ -0,0 +1,176 @@ +import { CrashedEvent } from './application'; +import { WindowEvent, BaseEventMap } from './base'; +export declare type SpecificWindowEvent = WindowEvent<'window', Type>; +export interface WindowAlertRequestedEvent extends WindowEvent { + message: string; + url: string; +} +export interface WindowAuthRequestedEvent extends WindowEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; +} +export interface WindowEndLoadEvent extends WindowEvent { + documentName: string; + isMain: boolean; +} +export interface WindowNavigationRejectedEvent extends WindowEvent { + sourceName: string; + url: string; +} +export interface WindowReloadedEvent extends WindowEvent { + url: string; +} +export interface WindowExternalProcessExitedEvent extends WindowEvent { + processUuid: string; + exitCode: number; +} +export interface WindowExternalProcessStartedEvent extends WindowEvent { + processUuid: string; +} +export interface WindowHiddenEvent extends WindowEvent { + reason: 'closing' | 'hide' | 'hide-on-close'; +} +export interface PreloadScriptInfoRunning { + state: 'load-started' | // started loading preload script + 'load-failed' | // preload script failed to load + 'load-succeeded' | // preload script is loaded and ready to be eval'ed + 'failed' | // preload script failed to eval + 'succeeded'; +} +export interface PreloadScriptInfo { + state: 'load-failed' | // preload script failed to load + 'failed' | // preload script failed to eval + 'succeeded'; +} +export interface WindowPreloadScriptsStateChangeEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfoRunning & any)[]; +} +export interface WindowPreloadScriptsStateChangedEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfoRunning & any)[]; +} +export interface WindowPreloadScriptsStateChangedEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfo & any)[]; +} +export interface WindowResourceLoadFailedEvent extends WindowEvent { + errorCode: number; + errorDescription: string; + validatedURL: string; + isMainFrame: boolean; +} +export interface WindowResourceResponseReceivedEvent extends WindowEvent { + status: boolean; + newUrl: string; + originalUrl: string; + httpResponseCode: number; + requestMethod: string; + referrer: string; + headers: any; + resourceType: 'mainFrame' | 'subFrame' | 'styleSheet' | 'script' | 'image' | 'object' | 'xhr' | 'other'; +} +export interface WindowBeginBoundsChangingEvent extends WindowEvent { + height: number; + left: number; + top: number; + width: number; + windowState: 'minimized' | 'normal' | 'maximized'; +} +export interface WindowBoundsChange extends WindowEvent { + changeType: 0 | 1 | 2; + deferred: boolean; + height: number; + left: number; + top: number; + width: number; +} +export interface WindowGroupChanged extends WindowEvent { + memberOf: 'source' | 'target' | 'nothing'; + reason: 'leave' | 'join' | 'merge' | 'disband'; + sourceGroup: { + appUuid: string; + windowName: string; + }[]; + sourceWindowAppUuid: string; + sourceWindowName: string; + targetGroup: { + appUuid: string; + windowName: string; + }[]; + targetWindowAppUuid: string; + targetWindowName: string; +} +export interface WindowEventMapping extends BaseEventMap { + 'auth-requested': WindowAuthRequestedEvent; + 'begin-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'blurred': WindowEvent; + 'bounds-changed': WindowBoundsChange; + 'bounds-changing': WindowBoundsChange; + 'close-requested': WindowEvent; + 'closed': WindowEvent; + 'closing': WindowEvent; + 'crashed': CrashedEvent & WindowEvent; + 'disabled-frame-bounds-changed': WindowBoundsChange; + 'disabled-frame-bounds-changing': WindowBoundsChange; + 'embedded': WindowEvent; + 'end-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'external-process-exited': WindowExternalProcessExitedEvent; + 'external-process-started': WindowExternalProcessStartedEvent; + 'focused': WindowEvent; + 'frame-disabled': WindowEvent; + 'frame-enabled': WindowEvent; + 'group-changed': WindowGroupChanged; + 'hidden': WindowHiddenEvent; + 'initialized': WindowEvent; + 'maximized': WindowEvent; + 'minimized': WindowEvent; + 'navigation-rejected': WindowNavigationRejectedEvent; + 'preload-scripts-state-changed': WindowPreloadScriptsStateChangeEvent; + 'preload-scripts-state-changing': WindowPreloadScriptsStateChangeEvent; + 'resource-load-failed': WindowResourceLoadFailedEvent; + 'resource-response-received': WindowResourceResponseReceivedEvent; + 'reloaded': WindowReloadedEvent; + 'restored': WindowEvent; + 'show-requested': WindowEvent; + 'shown': WindowEvent; +} +export interface PropagatedWindowEventMapping extends BaseEventMap { + 'window-begin-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'window-blurred': WindowEvent; + 'window-bounds-changed': WindowBoundsChange; + 'window-bounds-changing': WindowBoundsChange; + 'window-closed': WindowEvent; + 'window-closing': WindowEvent; + 'window-crashed': CrashedEvent & WindowEvent; + 'window-disabled-frame-bounds-changed': WindowBoundsChange; + 'window-disabled-frame-bounds-changing': WindowBoundsChange; + 'window-embedded': WindowEvent; + 'window-end-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'window-external-process-exited': WindowExternalProcessExitedEvent; + 'window-external-process-started': WindowExternalProcessStartedEvent; + 'window-focused': WindowEvent; + 'window-frame-disabled': WindowEvent; + 'window-frame-enabled': WindowEvent; + 'window-group-changed': WindowGroupChanged; + 'window-hidden': WindowHiddenEvent; + 'window-initialized': WindowEvent; + 'window-maximized': WindowEvent; + 'window-minimized': WindowEvent; + 'window-navigation-rejected': WindowNavigationRejectedEvent; + 'window-preload-scripts-state-changed': WindowPreloadScriptsStateChangeEvent; + 'window-preload-scripts-state-changing': WindowPreloadScriptsStateChangedEvent; + 'window-resource-load-failed': WindowResourceLoadFailedEvent; + 'window-resource-response-received': WindowResourceResponseReceivedEvent; + 'window-reloaded': WindowReloadedEvent; + 'window-restored': WindowEvent; + 'window-shown': WindowEvent; +} +export declare type WindowEvents = { + [Type in keyof WindowEventMapping]: WindowEventMapping<'window', Type>[Type]; +}; +export declare type PropagatedWindowEvents = { + [Type in keyof PropagatedWindowEventMapping]: PropagatedWindowEventMapping[Type]; +}; diff --git a/types/openfin/v37/_v2/api/external-application/external-application.d.ts b/types/openfin/v37/_v2/api/external-application/external-application.d.ts new file mode 100644 index 0000000000..a4f44851e9 --- /dev/null +++ b/types/openfin/v37/_v2/api/external-application/external-application.d.ts @@ -0,0 +1,44 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +import { ExternalApplicationEvents } from '../events/externalApplication'; +export interface ExternalApplicationInfo { + parent: Identity; +} +/** + * @lends ExternalApplication + */ +export default class ExternalApplicationModule extends Base { + /** + * Asynchronously returns an External Application object that represents an existing external application. + * @param {string} uuid The UUID of the external application to be wrapped + * @return {Promise.} + * @tutorial ExternalApplication.wrap + * @static + */ + wrap(uuid: string): Promise; + /** + * Synchronously returns an External Application object that represents an existing external application. + * @param {string} uuid The UUID of the external application to be wrapped + * @return {ExternalApplication} + * @tutorial ExternalApplication.wrapSync + * @static + */ + wrapSync(uuid: string): ExternalApplication; +} +/** + * @classdesc An ExternalApplication object representing an application. Allows + * the developer to create, execute, show and close an external application as + * well as listen to application events. + * @class + */ +export declare class ExternalApplication extends EmitterBase { + identity: Identity; + constructor(wire: Transport, identity: Identity); + /** + * Retrieves information about the external application. + * @return {Promise.} + * @tutorial ExternalApplication.getInfo + */ + getInfo(): Promise; +} diff --git a/types/openfin/v37/_v2/api/fin.d.ts b/types/openfin/v37/_v2/api/fin.d.ts new file mode 100644 index 0000000000..1bec2ffb4f --- /dev/null +++ b/types/openfin/v37/_v2/api/fin.d.ts @@ -0,0 +1,27 @@ +/// +import Transport from '../transport/transport'; +import { EventEmitter } from 'events'; +import System from './system/system'; +import _WindowModule from './window/window'; +import Application from './application/application'; +import InterApplicationBus from './interappbus/interappbus'; +import _NotificationModule from './notification/notification'; +import Clipbpard from './clipboard/clipboard'; +import ExternalApplication from './external-application/external-application'; +import _FrameModule from './frame/frame'; +import GlobalHotkey from './global-hotkey'; +import { Identity } from '../identity'; +export default class Fin extends EventEmitter { + private wire; + System: System; + Window: _WindowModule; + Application: Application; + InterApplicationBus: InterApplicationBus; + Notification: _NotificationModule; + Clipboard: Clipbpard; + ExternalApplication: ExternalApplication; + Frame: _FrameModule; + GlobalHotkey: GlobalHotkey; + readonly me: Identity; + constructor(wire: Transport); +} diff --git a/types/openfin/v37/_v2/api/frame/frame.d.ts b/types/openfin/v37/_v2/api/frame/frame.d.ts new file mode 100644 index 0000000000..8795ae190b --- /dev/null +++ b/types/openfin/v37/_v2/api/frame/frame.d.ts @@ -0,0 +1,69 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +import { FrameEvents } from '../events/frame'; +export declare type EntityType = 'window' | 'iframe' | 'external connection' | 'unknown'; +export interface FrameInfo { + uuid: string; + name: string; + entityType: EntityType; + parent: Identity; +} +/** + * @lends Frame + */ +export default class _FrameModule extends Base { + /** + * Asynchronously returns a reference to the specified frame. The frame does not have to exist + * @param {Identity} identity - the identity of the frame you want to wrap + * @return {Promise.<_Frame>} + * @tutorial Frame.wrap + * @static + */ + wrap(identity: Identity): Promise<_Frame>; + /** + * Synchronously returns a reference to the specified frame. The frame does not have to exist + * @param {Identity} identity - the identity of the frame you want to wrap + * @return {_Frame} + * @tutorial Frame.wrapSync + * @static + */ + wrapSync(identity: Identity): _Frame; + /** + * Asynchronously returns a reference to the current frame + * @return {Promise.<_Frame>} + * @tutorial Frame.getCurrent + * @static + */ + getCurrent(): Promise<_Frame>; + /** + * Synchronously returns a reference to the current frame + * @return {_Frame} + * @tutorial Frame.getCurrentSync + * @static + */ + getCurrentSync(): _Frame; +} +/** + * @classdesc Represents a way to interact with `iframes`. Facilitates discovery of current context + * (iframe or main window) as well as the ability to listen for frame-specific events. + * @class + * @alias Frame + */ +export declare class _Frame extends EmitterBase { + identity: Identity; + constructor(wire: Transport, identity: Identity); + /** + * Returns a frame info object for the represented frame + * @return {Promise.} + * @tutorial Frame.getInfo + */ + getInfo(): Promise; + /** + * Returns a frame info object representing the window that the referenced iframe is + * currently embedded in + * @return {Promise.} + * @tutorial Frame.getParentWindow + */ + getParentWindow(): Promise; +} diff --git a/types/openfin/v37/_v2/api/global-hotkey/index.d.ts b/types/openfin/v37/_v2/api/global-hotkey/index.d.ts new file mode 100644 index 0000000000..7aa08d6f20 --- /dev/null +++ b/types/openfin/v37/_v2/api/global-hotkey/index.d.ts @@ -0,0 +1,38 @@ +import { EmitterBase } from '../base'; +import Transport from '../../transport/transport'; +import { GlobalHotkeyEvents } from '../events/globalHotkey'; +export declare const enum nonHotkeyEvents { + REGISTERED = "registered", + UNREGISTERED = "unregistered" +} +/** + * The GlobalHotkey module can register/unregister a global hotkeys. + * @namespace + */ +export default class GlobalHotkey extends EmitterBase { + constructor(wire: Transport); + /** + * Registers a global hotkey with the operating system. + * @return {Promise.} + * @tutorial GlobalHotkey.register + */ + register(hotkey: string, listener: (...args: any[]) => void): Promise; + /** + * Unregisters a global hotkey with the operating system. + * @return {Promise.} + * @tutorial GlobalHotkey.unregister + */ + unregister(hotkey: string): Promise; + /** + * Unregisters all global hotkeys for the current application. + * @return {Promise.} + * @tutorial GlobalHotkey.unregisterAll + */ + unregisterAll(): Promise; + /** + * Checks if a given hotkey has been registered + * @return {Promise.} + * @tutorial GlobalHotkey.isRegistered + */ + isRegistered(hotkey: string): Promise; +} diff --git a/types/openfin/v37/_v2/api/interappbus/channel/channel.d.ts b/types/openfin/v37/_v2/api/interappbus/channel/channel.d.ts new file mode 100644 index 0000000000..1c9a502e12 --- /dev/null +++ b/types/openfin/v37/_v2/api/interappbus/channel/channel.d.ts @@ -0,0 +1,31 @@ +import { Identity } from '../../../identity'; +import Transport, { Message } from '../../../transport/transport'; +export interface ProviderIdentity extends Identity { + channelId: string; + isExternal?: boolean; + channelName: string; +} +export declare type Action = (() => any) | ((payload: any) => any) | ((payload: any, id: ProviderIdentity) => any); +export declare type Middleware = (() => any) | ((action: string) => any) | ((action: string, payload: any) => any) | ((action: string, payload: any, id: ProviderIdentity) => any); +export interface ChannelMessagePayload extends Identity { + action: string; + payload: any; +} +export declare class ChannelBase { + protected subscriptions: any; + defaultAction: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any; + private preAction; + private postAction; + private errorMiddleware; + private defaultSet; + protected send: (to: Identity, action: string, payload: any) => Promise>; + protected providerIdentity: ProviderIdentity; + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + processAction(action: string, payload: any, senderIdentity: ProviderIdentity): Promise; + beforeAction(func: Action): void; + onError(func: (e: any, action: string, id: Identity) => any): void; + afterAction(func: Action): void; + remove(action: string): void; + setDefaultAction(func: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any): void; + register(topic: string, listener: Action): boolean; +} diff --git a/types/openfin/v37/_v2/api/interappbus/channel/client.d.ts b/types/openfin/v37/_v2/api/interappbus/channel/client.d.ts new file mode 100644 index 0000000000..d1c128a349 --- /dev/null +++ b/types/openfin/v37/_v2/api/interappbus/channel/client.d.ts @@ -0,0 +1,6 @@ +import { ChannelBase, ProviderIdentity } from './channel'; +import Transport from '../../../transport/transport'; +export declare class ChannelClient extends ChannelBase { + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + dispatch(action: string, payload?: any): Promise; +} diff --git a/types/openfin/v37/_v2/api/interappbus/channel/index.d.ts b/types/openfin/v37/_v2/api/interappbus/channel/index.d.ts new file mode 100644 index 0000000000..2b2d963932 --- /dev/null +++ b/types/openfin/v37/_v2/api/interappbus/channel/index.d.ts @@ -0,0 +1,32 @@ +import { ChannelClient } from './client'; +import { Identity } from '../../../identity'; +import { ChannelProvider } from './provider'; +import { EmitterBase } from '../../base'; +import Transport, { Message, Payload } from '../../../transport/transport'; +import { ProviderIdentity } from './channel'; +import { ChannelEvents } from '../../events/channel'; +export interface ConnectOptions { + wait?: boolean; + payload?: any; +} +export interface ChannelPayload { + payload: Payload; +} +export interface ChannelMessage extends Message { + senderIdentity: Identity; + ackToSender: any; + providerIdentity: ProviderIdentity; + connectAction: boolean; +} +export declare class Channel extends EmitterBase { + private channelMap; + constructor(wire: Transport); + getAllChannels(): Promise; + onChannelConnect(listener: (...args: any[]) => void): Promise; + onChannelDisconnect(listener: (...args: any[]) => void): Promise; + connect(channelName: string, options?: ConnectOptions): Promise; + create(channelName: string): Promise; + onmessage: (msg: ChannelMessage) => boolean; + private processChannelMessage; + private processChannelConnection; +} diff --git a/types/openfin/v37/_v2/api/interappbus/channel/provider.d.ts b/types/openfin/v37/_v2/api/interappbus/channel/provider.d.ts new file mode 100644 index 0000000000..4b978c2781 --- /dev/null +++ b/types/openfin/v37/_v2/api/interappbus/channel/provider.d.ts @@ -0,0 +1,15 @@ +import { ChannelBase, ProviderIdentity } from './channel'; +import Transport from '../../../transport/transport'; +import { Identity } from '../../../main'; +export declare type ConnectionListener = (identity: Identity, connectionMessage?: any) => any; +export declare class ChannelProvider extends ChannelBase { + private connectListener; + private disconnectListener; + connections: Identity[]; + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + dispatch(to: Identity, action: string, payload: any): Promise; + processConnection(senderId: Identity, payload: any): Promise; + publish(action: string, payload: any): Promise[]; + onConnection(listener: ConnectionListener): void; + onDisconnection(listener: ConnectionListener): void; +} diff --git a/types/openfin/v37/_v2/api/interappbus/interappbus.d.ts b/types/openfin/v37/_v2/api/interappbus/interappbus.d.ts new file mode 100644 index 0000000000..48aaf7430c --- /dev/null +++ b/types/openfin/v37/_v2/api/interappbus/interappbus.d.ts @@ -0,0 +1,80 @@ +/// +import { Base } from '../base'; +import { Identity } from '../../identity'; +import Transport, { Message } from '../../transport/transport'; +import { EventEmitter } from 'events'; +import { Channel } from './channel/index'; +/** + * A messaging bus that allows for pub/sub messaging between different applications. + * @namespace +*/ +export default class InterApplicationBus extends Base { + Channel: Channel; + events: { + subscriberAdded: string; + subscriberRemoved: string; + }; + private refCounter; + protected emitter: EventEmitter; + on: any; + removeAllListeners: any; + constructor(wire: Transport); + /** + * Publishes a message to all applications running on OpenFin Runtime that + * are subscribed to the specified topic. + * @param { string } topic The topic on which the message is sent + * @param { any } message The message to be published. Can be either a primitive + * data type (string, number, or boolean) or composite data type (object, array) + * that is composed of other primitive or composite data types + * @return {Promise.} + * @tutorial InterApplicationBus.publish + */ + publish(topic: string, message: any): Promise; + /** + * Sends a message to a specific application on a specific topic. + * @param { object } destination The uuid of the application to which the message is sent + * @param { string } topic The topic on which the message is sent + * @param { any } message The message to be sent. Can be either a primitive data + * type (string, number, or boolean) or composite data type (object, array) that + * is composed of other primitive or composite data types + * @return {Promise.} + * @tutorial InterApplicationBus.send + */ + send(destination: Identity, topic: string, message: any): Promise; + /** + * Subscribes to messages from the specified application on the specified topic. + * If the subscription is for a uuid, [name], topic combination that has already + * been published to upon subscription you will receive the last 20 missed messages + * in the order they were published. + * @param { Identity } source This object is described in the Identity in the typedef + * @param { string } topic The topic on which the message is sent + * @param { function } listener A function that is called when a message has + * been received. It is passed the message, uuid and name of the sending application. + * The message can be either a primitive data type (string, number, or boolean) or + * composite data type (object, array) that is composed of other primitive or composite + * data types + * @return {Promise.} + * @tutorial InterApplicationBus.subcribe + */ + subscribe(source: Identity, topic: string, listener: any): Promise; + /** + * Unsubscribes to messages from the specified application on the specified topic. + * @param { Identity } source This object is described in the Identity in the typedef + * @param { string } topic The topic on which the message is sent + * @param { function } listener A callback previously registered with subscribe() + * @return {Promise.} + * @tutorial InterApplicationBus.unsubscribe + */ + unsubscribe(source: Identity, topic: string, listener: any): Promise; + private processMessage; + private emitSubscriverEvent; + protected createSubscriptionKey(uuid: string, name: string, topic: string): string; + protected onmessage(message: Message): boolean; +} +export declare class InterAppPayload { + sourceUuid: string; + sourceWindowName: string; + topic: string; + destinationUuid?: string; + message?: any; +} diff --git a/types/openfin/v37/_v2/api/notification/notification.d.ts b/types/openfin/v37/_v2/api/notification/notification.d.ts new file mode 100644 index 0000000000..9a6bee7076 --- /dev/null +++ b/types/openfin/v37/_v2/api/notification/notification.d.ts @@ -0,0 +1,70 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +import { NotificationEvents } from '../events/notifications'; +export declare class NotificationOptions { + url: string; + message: string; + timeout: string | number; + notificationId: number; + uuidOfProxiedApp: string; + ignoreMouseOver: boolean; + constructor(options: any, identity: Identity, notificationId: number); +} +export interface NotificationCallback { + message?: any; +} +/** + * @classdesc A Notification object represents a window on OpenFin Runtime which + * is shown briefly to the user on the bottom-right corner of the primary monitor. + * A notification is typically used to alert the user of some important event which + * requires his or her attention. Notifications are a child or your application that + * are controlled by the runtime. + * @class + * @alias Notification + */ +export declare class _Notification extends EmitterBase { + private listenerList; + private unhookAllListeners; + protected options: NotificationOptions; + protected generalListener: (msg: any) => void; + protected notificationId: number; + constructor(wire: Transport, options: NotificationOptions); + url: string; + timeout: number | string; + message: any; + /** + * Invoked when the notification is shown + * @return {Promise.} + * @tutorial Notification.show + */ + show(): Promise; + /** + * Sends a message to the notification. + * @param { any } message The message to be sent to the notification. + * Can be either a primitive data type (string, number, or boolean) + * or composite data type (object, array) that is composed of other + * primitive or composite data types + * @return {Promise.} + * @tutorial Notification.sendMessage + */ + sendMessage(message: any): Promise; + /** + * Closes the notification + * @return {Promise.} + * @tutorial Notification.close + */ + close(): Promise; +} +export default class _NotificationModule extends Base { + private nextNoteId; + private genNoteId; + events: { + show: string; + close: string; + error: string; + click: string; + message: string; + }; + create(options: any): _Notification; +} diff --git a/types/openfin/v37/_v2/api/system/application.d.ts b/types/openfin/v37/_v2/api/system/application.d.ts new file mode 100644 index 0000000000..0e14602942 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/application.d.ts @@ -0,0 +1,5 @@ +export interface ApplicationInfo { + isRunning: boolean; + uuid: string; + parentUuid?: string; +} diff --git a/types/openfin/v37/_v2/api/system/clearCacheOption.d.ts b/types/openfin/v37/_v2/api/system/clearCacheOption.d.ts new file mode 100644 index 0000000000..6bae8116b7 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/clearCacheOption.d.ts @@ -0,0 +1,6 @@ +export interface ClearCacheOption { + appcache?: boolean; + cache?: boolean; + cookies?: boolean; + localStorage?: boolean; +} diff --git a/types/openfin/v37/_v2/api/system/cookie.d.ts b/types/openfin/v37/_v2/api/system/cookie.d.ts new file mode 100644 index 0000000000..1d229232c6 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/cookie.d.ts @@ -0,0 +1,8 @@ +export interface CookieInfo { + name: string; + domain: string; + path: string; +} +export interface CookieOption { + name: string; +} diff --git a/types/openfin/v37/_v2/api/system/crashReporterOption.d.ts b/types/openfin/v37/_v2/api/system/crashReporterOption.d.ts new file mode 100644 index 0000000000..7d512fdd7b --- /dev/null +++ b/types/openfin/v37/_v2/api/system/crashReporterOption.d.ts @@ -0,0 +1,4 @@ +export interface CrashReporterOption { + diagnosticMode: boolean; + isRunning?: boolean; +} diff --git a/types/openfin/v37/_v2/api/system/download-asset.d.ts b/types/openfin/v37/_v2/api/system/download-asset.d.ts new file mode 100644 index 0000000000..be513f5f0e --- /dev/null +++ b/types/openfin/v37/_v2/api/system/download-asset.d.ts @@ -0,0 +1,18 @@ +export interface AppAssetInfo { + src: string; + alias: string; + version: string; + target?: string; + args?: string; + mandatory?: boolean; +} +export interface RuntimeDownloadOptions { + version: string; +} +export interface AppAssetRequest { + alias: string; +} +export interface RuntimeDownloadProgress { + downloadedBytes: number; + totalBytes: number; +} diff --git a/types/openfin/v37/_v2/api/system/download-preload.d.ts b/types/openfin/v37/_v2/api/system/download-preload.d.ts new file mode 100644 index 0000000000..a7e635bcb8 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/download-preload.d.ts @@ -0,0 +1,8 @@ +export interface DownloadPreloadOption { + url: string; +} +export interface DownloadPreloadInfo { + success: boolean; + url?: string; + error: string; +} diff --git a/types/openfin/v37/_v2/api/system/entity.d.ts b/types/openfin/v37/_v2/api/system/entity.d.ts new file mode 100644 index 0000000000..50011a64f3 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/entity.d.ts @@ -0,0 +1,11 @@ +import { Identity } from '../../identity'; +export interface Entity { + type: string; + uuid: string; +} +export interface EntityInfo { + name: string; + uuid: string; + parent: Identity; + entityType: string; +} diff --git a/types/openfin/v37/_v2/api/system/external-process.d.ts b/types/openfin/v37/_v2/api/system/external-process.d.ts new file mode 100644 index 0000000000..624c93ea18 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/external-process.d.ts @@ -0,0 +1,36 @@ +export interface ExternalProcessRequestType { + path?: string; + alias?: string; + arguments?: string; + listener?: LaunchExternalProcessListener; + lifetime?: string; + certificate?: CertificationInfo; +} +export interface CertificationInfo { + serial?: string; + subject?: string; + publickey?: string; + thumbprint?: string; + trusted?: boolean; +} +export interface ExitCode { + topic: string; + uuid: string; + exitCode: number; +} +export interface LaunchExternalProcessListener { + (code: ExitCode): void; +} +export interface TerminateExternalRequestType { + uuid: string; + timeout: number; + killTree: boolean; +} +export interface ExternalConnection { + token: string; + uuid: string; +} +export interface ExternalProcessInfo { + pid: number; + listener?: LaunchExternalProcessListener; +} diff --git a/types/openfin/v37/_v2/api/system/host-specs.d.ts b/types/openfin/v37/_v2/api/system/host-specs.d.ts new file mode 100644 index 0000000000..dfd3e665fd --- /dev/null +++ b/types/openfin/v37/_v2/api/system/host-specs.d.ts @@ -0,0 +1,24 @@ +export interface Time { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; +} +export interface CpuInfo { + model: string; + speed: number; + times: Time; +} +export interface GpuInfo { + name: string; +} +export interface HostSpecs { + aeroGlassEnabled?: boolean; + arch: string; + cpus: CpuInfo[]; + gpu: GpuInfo; + memory: number; + name: string; + screenSaver?: boolean; +} diff --git a/types/openfin/v37/_v2/api/system/log.d.ts b/types/openfin/v37/_v2/api/system/log.d.ts new file mode 100644 index 0000000000..9b03b28c57 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/log.d.ts @@ -0,0 +1,11 @@ +export interface GetLogRequestType { + name: string; + endFile?: string; + sizeLimit?: number; +} +export interface LogInfo { + name: string; + size: number; + date: string; +} +export declare type LogLevel = 'verbose' | 'info' | 'warning' | 'error' | 'fatal'; diff --git a/types/openfin/v37/_v2/api/system/monitor.d.ts b/types/openfin/v37/_v2/api/system/monitor.d.ts new file mode 100644 index 0000000000..ea4aed799c --- /dev/null +++ b/types/openfin/v37/_v2/api/system/monitor.d.ts @@ -0,0 +1,39 @@ +import { Point } from './point'; +export interface MonitorInfo { + deviceScaleFactor: number; + dpi: Point; + nonPrimaryMonitors: Array; + primaryMonitor: MonitorDetails; + reason: string; + taskBar: TaskBar; + virtualScreen: DipRect; +} +export interface MonitorDetails { + available: DipScaleRects; + availableRect: Rect; + deviceId: string; + displayDeviceActive: boolean; + deviceScaleFactor: number; + monitorRect: Rect; + name: number; + dpi: Point; + monitor: DipScaleRects; +} +export interface Rect { + bottom: number; + left: number; + right: number; + top: number; +} +export interface DipRect extends Rect { + dipRect: Rect; + scaledRect: Rect; +} +export interface DipScaleRects { + dipRect: Rect; + scaledRect: Rect; +} +export interface TaskBar extends DipScaleRects { + edge: string; + rect: Rect; +} diff --git a/types/openfin/v37/_v2/api/system/point.d.ts b/types/openfin/v37/_v2/api/system/point.d.ts new file mode 100644 index 0000000000..b9830ce514 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/point.d.ts @@ -0,0 +1,8 @@ +export interface Point { + x: number; + y: number; +} +export interface PointTopLeft { + top: number; + left: number; +} diff --git a/types/openfin/v37/_v2/api/system/process.d.ts b/types/openfin/v37/_v2/api/system/process.d.ts new file mode 100644 index 0000000000..98901db137 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/process.d.ts @@ -0,0 +1,15 @@ +export interface ProcessInfo { + cpuUsage?: number; + name?: string; + nonPagedPoolUsage?: number; + pageFaultCount?: number; + pagedPoolUsage?: number; + pagefileUsage?: number; + peakNonPagedPoolUsage?: number; + peakPagedPoolUsage?: number; + peakPagefileUsage?: number; + peakWorkingSetSize?: number; + processId?: number; + uuid?: string; + workingSetSize?: number; +} diff --git a/types/openfin/v37/_v2/api/system/proxy.d.ts b/types/openfin/v37/_v2/api/system/proxy.d.ts new file mode 100644 index 0000000000..2f8a945903 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/proxy.d.ts @@ -0,0 +1,15 @@ +export interface ProxyInfo { + config: ProxyConfig; + system: ProxySystemInfo; +} +export interface ProxyConfig { + proxyAddress: string; + proxyPort: number; + type: string; +} +export interface ProxySystemInfo { + autoConfigUrl: string; + bypass: string; + enabled: boolean; + proxy: string; +} diff --git a/types/openfin/v37/_v2/api/system/registry-info.d.ts b/types/openfin/v37/_v2/api/system/registry-info.d.ts new file mode 100644 index 0000000000..a48ed34959 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/registry-info.d.ts @@ -0,0 +1,7 @@ +export interface RegistryInfo { + data: any; + rootKey: string; + subkey: string; + type: string; + value: string; +} diff --git a/types/openfin/v37/_v2/api/system/runtime-info.d.ts b/types/openfin/v37/_v2/api/system/runtime-info.d.ts new file mode 100644 index 0000000000..1508f87ef3 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/runtime-info.d.ts @@ -0,0 +1,7 @@ +export interface RuntimeInfo { + architecture: string; + manifestUrl: string; + port: number; + securityRealm?: string; + version: string; +} diff --git a/types/openfin/v37/_v2/api/system/rvm.d.ts b/types/openfin/v37/_v2/api/system/rvm.d.ts new file mode 100644 index 0000000000..fb8737a081 --- /dev/null +++ b/types/openfin/v37/_v2/api/system/rvm.d.ts @@ -0,0 +1,8 @@ +export interface RVMInfo { + action: string; + appLogDirectory: string; + path: string; + 'start-time': string; + version: string; + 'working-dir': string; +} diff --git a/types/openfin/v37/_v2/api/system/system.d.ts b/types/openfin/v37/_v2/api/system/system.d.ts new file mode 100644 index 0000000000..76f244cabf --- /dev/null +++ b/types/openfin/v37/_v2/api/system/system.d.ts @@ -0,0 +1,588 @@ +import { EmitterBase } from '../base'; +import { ApplicationInfo } from './application'; +import { WindowInfo } from './window'; +import { Identity } from '../../identity'; +import { MonitorInfo } from './monitor'; +import { PointTopLeft } from './point'; +import { GetLogRequestType, LogInfo, LogLevel } from './log'; +import { ProxyInfo, ProxyConfig } from './proxy'; +import { ProcessInfo } from './process'; +import { AppAssetInfo, AppAssetRequest, RuntimeDownloadOptions, RuntimeDownloadProgress } from './download-asset'; +import { RVMInfo } from './rvm'; +import { RuntimeInfo } from './runtime-info'; +import { Entity, EntityInfo } from './entity'; +import { HostSpecs } from './host-specs'; +import { ExternalProcessRequestType, TerminateExternalRequestType, ExternalConnection, ExternalProcessInfo } from './external-process'; +import Transport from '../../transport/transport'; +import { CookieInfo, CookieOption } from './cookie'; +import { RegistryInfo } from './registry-info'; +import { DownloadPreloadOption, DownloadPreloadInfo } from './download-preload'; +import { ClearCacheOption } from './clearCacheOption'; +import { CrashReporterOption } from './crashReporterOption'; +import { SystemEvents } from '../events/system'; +/** + * AppAssetInfo interface + * @typedef { Object } AppAssetInfo + * @property { string } src The URL to a zip file containing the package files (executables, dlls, etc…) + * @property { string } alias The name of the asset + * @property { string } version The version of the package + * @property { string } target Specify default executable to launch. This option can be overridden in launchExternalProcess + * @property { args } args The default command line arguments for the aforementioned target. + * @property { boolean } mandatory When set to true, the app will fail to load if the asset cannot be downloaded. + * When set to false, the app will continue to load if the asset cannot be downloaded. (Default: true) + */ +/** + * AppAssetRequest interface + * @typedef { Object } AppAssetRequest + * @property { string } alias The name of the asset + */ +/** + * ApplicationInfo interface + * @typedef { Object } ApplicationInfo + * @property { boolean } isRunning true when the application is running + * @property { string } uuid uuid of the application + * @property { string } parentUuid uuid of the application that launches this application + */ +/** + * @typedef { Object } ClearCacheOption + * @summary Clear cache options. + * @desc These are the options required by the clearCache function. + * + * @property {boolean} appcache html5 application cache + * @property {boolean} cache browser data cache for html files and images + * @property {boolean} cookies browser cookies + * @property {boolean} localStorage browser data that can be used across sessions + */ +/** + * CookieInfo interface + * @typedef { Object } CookieInfo + * @property { string } name The name of the cookie + * @property { string } domain The domain of the cookie + * @property { string } path The path of the cookie + */ +/** + * CookieOption interface + * @typedef { Object } CookieOption + * @property { string } name The name of the cookie + */ +/** + * CpuInfo interface + * @typedef { Object } CpuInfo + * @property { string } model The model of the cpu + * @property { number } speed The number in MHz + * @property { Time } times The numbers of milliseconds the CPU has spent in different modes. + */ +/** +* CrashReporterOption interface +* @typedef { Object } CrashReporterOption +* @property { boolean } diagnosticMode In diagnostic mode the crash reporter will send diagnostic logs to +* the OpenFin reporting service on runtime shutdown +* @property { boolean } isRunning check if it's running +*/ +/** + * DownloadPreloadInfo interface + * @typedef { Object } DownloadPreloadInfo + * @desc downloadPreloadScripts function return value + * @property { string } url url to the preload script + * @property { string } error error during preload script acquisition + * @property { boolean } succeess download operation success + */ +/** + * DownloadPreloadOption interface + * @typedef { Object } DownloadPreloadOption + * @desc These are the options object required by the downloadPreloadScripts function + * @property { string } url url to the preload script + */ +/** + * Entity interface + * @typedef { Object } Entity + * @property { string } type The type of the entity + * @property { string } uuid The uuid of the entity + */ +/** + * EntityInfo interface + * @typedef { Object } EntityInfo + * @property { string } name The name of the entity + * @property { string } uuid The uuid of the entity + * @property { Identity } parent The parent of the entity + * @property { string } entityType The type of the entity + */ +/** + * ExternalConnection interface + * @typedef { Object } ExternalConnection + * @property { string } token The token to broker an external connection + * @property { string } uuid The uuid of the external connection + */ +/** + * ExternalProcessRequestType interface + * @typedef { Object } ExternalProcessRequestType + * @property { string } path The file path to where the running application resides + * @property { string } arguments The argument passed to the running application + * @property { Object } listener This is described in the {LaunchExternalProcessListner} type definition + */ +/** + * GetLogRequestType interface + * @typedef { Object } GetLogRequestType + * @property { string } name The name of the running application + * @property { number } endFile The file length of the log file + * @property { number } sizeLimit The set size limit of the log file + */ +/** + * GpuInfo interface + * @typedef { Object } GpuInfo + * @property { string } name The graphics card name + */ +/** + * HostSpecs interface + * @typedef { Object } HostSpecs + * @property { boolean } aeroGlassEnabled Value to check if Aero Glass theme is supported on Windows platforms + * @property { string } arch "x86" for 32-bit or "x86_64" for 64-bit + * @property { Array } cpus The same payload as Node's os.cpus() + * @property { GpuInfo } gpu The graphics card name + * @property { number } memory The same payload as Node's os.totalmem() + * @property { string } name The OS name and version/edition + * @property { boolean } screenSaver Value to check if screensaver is running. Supported on Windows only + */ +/** + * Identity interface + * @typedef { Object } Identity + * @property { string } name The name of the application + * @property { string } uuid The uuid of the application + */ +/** + * LogInfo interface + * @typedef { Object } LogInfo + * @property { string } name The filename of the log + * @property { number } size The size of the log in bytes + * @property { string } date The unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)"" + */ +/** + * @typedef { verbose | info | warning | error | fatal } LogLevel + * @summary Log verbosity levels. + * @desc Describes the minimum level (inclusive) above which logs will be written + * + * @property { string } verbose all logs written + * @property { string } info info and above + * @property { string } warning warning and above + * @property { string } error error and above + * @property { string } fatal fatal only, indicates a crash is imminent + */ +/** + * PointTopLeft interface + * @typedef { Object } PointTopLeft + * @property { number } top The mouse top position in virtual screen coordinates + * @property { number } left The mouse left position in virtual screen coordinates + */ +/** + * ProcessInfo interface + * @typedef { Object } ProcessInfo + * @property { numder } cpuUsage The percentage of total CPU usage + * @property { string } name The application name + * @property { number } nonPagedPoolUsage The current nonpaged pool usage in bytes + * @property { number } pageFaultCount The number of page faults + * @property { number } pagedPoolUsage The current paged pool usage in bytes + * @property { number } pagefileUsage The total amount of memory in bytes that the memory manager has committed + * @property { number } peakNonPagedPoolUsage The peak nonpaged pool usage in bytes + * @property { number } peakPagedPoolUsage The peak paged pool usage in bytes + * @property { number } peakPagefileUsage The peak value in bytes of pagefileUsage during the lifetime of this process + * @property { number } peakWorkingSetSize The peak working set size in bytes + * @property { number } processId The native process identifier + * @property { string } uuid The application UUID + * @property { nubmer } workingSetSize The current working set size (both shared and private data) in bytes + */ +/** + * ProxyConfig interface + * @typedef { Object } ProxyConfig + * @property { string } proxyAddress The configured proxy address + * @property { numder } proxyPort The configured proxy port + * @property { string } type The proxy Type + */ +/** + * ProxyInfo interface + * @typedef { Object } ProxyInfo + * @property { ProxyConfig } config The proxy config + * @property { ProxySystemInfo } system The proxy system info + */ +/** + * ProxySystemInfo interface + * @typedef { Object } ProxySystemInfo + * @property { string } autoConfigUrl The auto configuration url + * @property { string } bypass The proxy bypass info + * @property { boolean } enabled Value to check if a proxy is enabled + * @property { string } proxy The proxy info + */ +/** + * RegistryInfo interface + * @typedef { Object } RegistryInfo + * @property { any } data The registry data + * @property { string } rootKey The registry root key + * @property { string } subkey The registry key + * @property { string } type The registry type + * @property { string } value The registry value name + */ +/** + * RuntimeDownloadOptions interface + * @typedef { Object } RuntimeDownloadOptions + * @desc These are the options object required by the downloadRuntime function. + * @property { string } version The given version to download + */ +/** + * RVMInfo interface + * @typedef { Object } RVMInfo + * @property { string } action The name of action: "get-rvm-info" + * @property { string } appLogDirectory The app log directory + * @property { string } path The path of OpenfinRVM.exe + * @property { string } 'start-time' The start time of RVM + * @property { string } version The version of RVM + * @property { string } 'working-dir' The working directory + */ +/** + * TerminateExternalRequestType interface + * @typedef { Object } TerminateExternalRequestType + * @property { string } uuid The uuid of the running application + * @property { number } timeout Time out period before the running application terminates + * @property { boolean } killtree Value to terminate the running application + */ +/** + * Time interface + * @typedef { Object } Time + * @property { number } user The number of milliseconds the CPU has spent in user mode + * @property { number } nice The number of milliseconds the CPU has spent in nice mode + * @property { number } sys The number of milliseconds the CPU has spent in sys mode + * @property { number } idle The number of milliseconds the CPU has spent in idle mode + * @property { number } irq The number of milliseconds the CPU has spent in irq mode + */ +/** + * WindowDetail interface + * @typedef { Object } WindowDetail + * @property { number } bottom The bottom-most coordinate of the window + * @property { number } height The height of the window + * @property { boolean } isShowing Value to check if the window is showing + * @property { number } left The left-most coordinate of the window + * @property { string } name The name of the window + * @property { number } right The right-most coordinate of the window + * @property { string } state The window state + * @property { number } top The top-most coordinate of the window + * @property { number } width The width of the window + */ +/** + * WindowInfo interface + * @typedef { Object } WindowInfo + * @property { Array } childWindows The array of child windows details + * @property { WindowDetail } mainWindow The main window detail + * @property { string } uuid The uuid of the application + */ +/** + * An object representing the core of OpenFin Runtime. Allows the developer + * to perform system-level actions, such as accessing logs, viewing processes, + * clearing the cache and exiting the runtime. + * @namespace + */ +export default class System extends EmitterBase { + constructor(wire: Transport); + /** + * Returns the version of the runtime. The version contains the major, minor, + * build and revision numbers. + * @return {Promise.} + * @tutorial System.getVersion + */ + getVersion(): Promise; + /** + * Clears cached data containing application resource + * files (images, HTML, JavaScript files), cookies, and items stored in the + * Local Storage. + * @param { ClearCacheOption } options - See tutorial for more details. + * @return {Promise.} + * @tutorial System.clearCache + */ + clearCache(options: ClearCacheOption): Promise; + /** + * Clears all cached data when OpenFin Runtime exits. + * @return {Promise.} + * @tutorial System.deleteCacheOnExit + */ + deleteCacheOnExit(): Promise; + /** + * Exits the Runtime. + * @return {Promise.} + * @tutorial System.exit + */ + exit(): Promise; + /** + * Writes any unwritten cookies data to disk. + * @return {Promise.} + * @tutorial System.flushCookieStore + */ + flushCookieStore(): Promise; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + * @return {Promise.Array.} + * @tutorial System.getAllWindows + */ + getAllWindows(): Promise>; + /** + * Retrieves an array of data for all applications. + * @return {Promise.Array.} + * @tutorial System.getAllApplications + */ + getAllApplications(): Promise>; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + * @return {Promise.} + * @tutorial System.getCommandLineArguments + */ + getCommandLineArguments(): Promise; + /** + * Get the current state of the crash reporter. + * @return {Promise.} + * @tutorial System.getCrashReporterState + */ + getCrashReporterState(): Promise; + getDeviceId(): Promise; + /** + * Start the crash reporter for the browser process if not already running. + * You can optionally specify `diagnosticMode` to have the logs sent to + * OpenFin on runtime close + * + * @param { CrashReporterOption } options - configure crash reporter + * @return {Promise.} + * @tutorial System.startCrashReporter + */ + startCrashReporter(options: CrashReporterOption): Promise; + /** + * Returns a hex encoded hash of the mac address and the currently logged in user name + * @return {Promise.} + * @tutorial System.getDeviceUserId + */ + getDeviceUserId(): Promise; + /** + * Retrieves a frame info object for the uuid and name passed in + * @param { string } uuid - The UUID of the target. + * @param { string } name - The name of the target. + * @return {Promise.} + * @tutorial System.getEntityInfo + */ + getEntityInfo(uuid: string, name: string): Promise; + /** + * Gets the value of a given environment variable on the computer on which the runtime is installed + * @return {Promise.} + * @tutorial System.getEnvironmentVariable + */ + getEnvironmentVariable(envName: string): Promise; + /** + * Get current focused window. + * @return {Promise.} + * @tutorial System.getFocusedWindow + */ + getFocusedWindow(): Promise; + /** + * Retrieves the contents of the log with the specified filename. + * @param { GetLogRequestType } options A object that id defined by the GetLogRequestType interface + * @return {Promise.} + * @tutorial System.getLog + */ + getLog(options: GetLogRequestType): Promise; + /** + * Returns a unique identifier (UUID) provided by the machine. + * @return {Promise.} + * @tutorial System.getMachineId + */ + getMachineId(): Promise; + /** + * Returns the minimum (inclusive) logging level that is currently being written to the log. + * @return {Promise.} + * @tutorial System.getMinLogLevel + */ + getMinLogLevel(): Promise; + /** + * Retrieves an array containing information for each log file. + * @return {Promise.Array} + * @tutorial System.getLogList + */ + getLogList(): Promise>; + /** + * Retrieves an object that contains data about the monitor setup of the + * computer that the runtime is running on. + * @return {Promise.} + * @tutorial System.getMonitorInfo + */ + getMonitorInfo(): Promise; + /** + * Returns the mouse in virtual screen coordinates (left, top). + * @return {Promise.} + * @tutorial System.getMousePosition + */ + getMousePosition(): Promise; + /** + * Retrieves an array of all of the runtime processes that are currently + * running. Each element in the array is an object containing the uuid + * and the name of the application to which the process belongs. + * @return {Promise.Array.} + * @tutorial System.getProcessList + */ + getProcessList(): Promise>; + /** + * Retrieves the Proxy settings. + * @return {Promise.} + * @tutorial System.getProxySettings + */ + getProxySettings(): Promise; + /** + * Returns information about the running Runtime in an object. + * @return {Promise.} + * @tutorial System.getRuntimeInfo + */ + getRuntimeInfo(): Promise; + /** + * Returns information about the running RVM in an object. + * @return {Promise.} + * @tutorial System.getRvmInfo + */ + getRvmInfo(): Promise; + /** + * Retrieves system information. + * @return {Promise.} + * @tutorial System.getHostSpecs + */ + getHostSpecs(): Promise; + /** + * Runs an executable or batch file. + * @param { ExternalProcessRequestType } options A object that is defined in the ExternalProcessRequestType interface + * @return {Promise.} + * @tutorial System.launchExternalProcess + */ + launchExternalProcess(options: ExternalProcessRequestType): Promise; + /** + * Monitors a running process. + * @param { ExternalProcessInfo } options See tutorial for more details + * @return {Promise.} + * @tutorial System.monitorExternalProcess + */ + monitorExternalProcess(options: ExternalProcessInfo): Promise; + /** + * Writes the passed message into both the log file and the console. + * @param { string } level The log level for the entry. Can be either "info", "warning" or "error" + * @param { string } message The log message text + * @return {Promise.} + * @tutorial System.log + */ + log(level: string, message: string): Promise; + /** + * Opens the passed URL in the default web browser. + * @param { string } url The URL to open + * @return {Promise.} + * @tutorial System.openUrlWithBrowser + */ + openUrlWithBrowser(url: string): Promise; + /** + * Removes the process entry for the passed UUID obtained from a prior call + * of fin.System.launchExternalProcess(). + * @param { string } uuid The UUID for a process obtained from a prior call to fin.desktop.System.launchExternalProcess() + * @return {Promise.} + * @tutorial System.releaseExternalProcess + */ + releaseExternalProcess(uuid: string): Promise; + /** + * Shows the Chromium Developer Tools for the specified window + * @param { Identity } identity This is a object that is defined by the Identity interface + * @return {Promise.} + * @tutorial System.showDeveloperTools + */ + showDeveloperTools(identity: Identity): Promise; + /** + * Attempt to close an external process. The process will be terminated if it + * has not closed after the elapsed timeout in milliseconds. + * @param { TerminateExternalRequestType } options A object defined in the TerminateExternalRequestType interface + * @return {Promise.} + * @tutorial System.terminateExternalProcess + */ + terminateExternalProcess(options: TerminateExternalRequestType): Promise; + /** + * Update the OpenFin Runtime Proxy settings. + * @param { ProxyConfig } options A config object defined in the ProxyConfig interface + * @return {Promise.} + * @tutorial System.updateProxySettings + */ + updateProxySettings(options: ProxyConfig): Promise; + /** + * Downloads the given application asset + * @param { AppAssetInfo } appAsset App asset object + * @return {Promise.} + * @tutorial System.downloadAsset + */ + downloadAsset(appAsset: AppAssetInfo, progressListener: (progress: RuntimeDownloadProgress) => void): Promise; + /** + * Downloads a version of the runtime. + * @param { RuntimeDownloadOptions } options - Download options. + * @param {Function} [progressListener] - called as the runtime is downloaded with progress information. + * @return {Promise.} + * @tutorial System.downloadRuntime + */ + downloadRuntime(options: RuntimeDownloadOptions, progressListener: (progress: RuntimeDownloadProgress) => void): Promise; + /** + * Download preload scripts from given URLs + * @param {DownloadPreloadOption[]} scripts - URLs of preload scripts. See tutorial for more details. + * @return {Promise.Array} + * @tutorial System.downloadPreloadScripts + */ + downloadPreloadScripts(scripts: Array): Promise>; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + * @return {Promise.Array.} + * @tutorial System.getAllExternalApplications + */ + getAllExternalApplications(): Promise>; + /** + * Retrieves app asset information. + * @param { AppAssetRequest } options + * @return {Promise.} + * @tutorial System.getAppAssetInfo + */ + getAppAssetInfo(options: AppAssetRequest): Promise; + /** + * Get additional info of cookies. + * @param { CookieOption } options - See tutorial for more details. + * @return {Promise.Array.} + * @tutorial System.getCookies + */ + getCookies(options: CookieOption): Promise>; + /** + * Set the minimum log level above which logs will be written to the OpenFin log + * @param { LogLevel } The minimum level (inclusive) above which all calls to log will be written + * @return {Promise.} + * @tutorial System.setMinLogLevel + */ + setMinLogLevel(level: LogLevel): Promise; + /** + * Retrieves the UUID of the computer on which the runtime is installed + * @param { string } uuid The uuid of the running application + * @return {Promise.} + * @tutorial System.resolveUuid + */ + resolveUuid(uuid: string): Promise; + /** + * Retrieves an array of data for all external applications + * @param { Identity } requestingIdentity This object is described in the Identity typedef + * @param { any } data Any data type to pass to the method + * @return {Promise.} + * @ignore + */ + executeOnRemote(requestingIdentity: Identity, data: any): Promise; + /** + * Reads the specifed value from the registry. + * @param { string } rootKey - The registry root key. + * @param { string } subkey - The registry key. + * @param { string } value - The registry value name. + * @return {Promise.} + * @tutorial System.readRegistryValue + */ + readRegistryValue(rootKey: string, subkey: string, value: string): Promise; + /** + * This function call will register a unique id and produce a token. + * The token can be used to broker an external connection. + * @param { string } uuid - A UUID for the remote connection. + * @return {Promise.} + * @tutorial System.registerExternalConnection + */ + registerExternalConnection(uuid: string): Promise; +} diff --git a/types/openfin/v37/_v2/api/system/window.d.ts b/types/openfin/v37/_v2/api/system/window.d.ts new file mode 100644 index 0000000000..7b2a3b858b --- /dev/null +++ b/types/openfin/v37/_v2/api/system/window.d.ts @@ -0,0 +1,16 @@ +export interface WindowInfo { + childWindows: Array; + mainWindow: WindowDetail; + uuid: string; +} +export interface WindowDetail { + bottom: number; + height: number; + isShowing: boolean; + left: number; + name: string; + right: number; + state: string; + top: number; + width: number; +} diff --git a/types/openfin/v37/_v2/api/window/anchor-type.d.ts b/types/openfin/v37/_v2/api/window/anchor-type.d.ts new file mode 100644 index 0000000000..4e09af40ab --- /dev/null +++ b/types/openfin/v37/_v2/api/window/anchor-type.d.ts @@ -0,0 +1 @@ +export declare type AnchorType = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; diff --git a/types/openfin/v37/_v2/api/window/bounds-changed.d.ts b/types/openfin/v37/_v2/api/window/bounds-changed.d.ts new file mode 100644 index 0000000000..f7801da3fc --- /dev/null +++ b/types/openfin/v37/_v2/api/window/bounds-changed.d.ts @@ -0,0 +1,14 @@ +import { Reply } from '../base'; +export default class BoundsChangedReply extends Reply<'window', 'bounds-changed'> { + changeType: BoundsChangeType; + deferred: boolean; + height: number; + width: number; + top: number; + left: number; +} +export declare const enum BoundsChangeType { + POSITION = 0, + SIZE = 1, + POSITION_AND_SIZE = 2 +} diff --git a/types/openfin/v37/_v2/api/window/bounds.d.ts b/types/openfin/v37/_v2/api/window/bounds.d.ts new file mode 100644 index 0000000000..40822c4aa3 --- /dev/null +++ b/types/openfin/v37/_v2/api/window/bounds.d.ts @@ -0,0 +1,9 @@ +interface Bounds { + height: number; + width: number; + top: number; + left: number; + right?: number; + bottom?: number; +} +export default Bounds; diff --git a/types/openfin/v37/_v2/api/window/transition.d.ts b/types/openfin/v37/_v2/api/window/transition.d.ts new file mode 100644 index 0000000000..c16440c80d --- /dev/null +++ b/types/openfin/v37/_v2/api/window/transition.d.ts @@ -0,0 +1,24 @@ +export interface TransitionBase { + duration: number; + relative?: boolean; +} +export interface Opacity extends TransitionBase { + opacity: number; +} +export interface Position extends TransitionBase { + left: number; + top: number; +} +export interface Size extends TransitionBase { + width: number; + height: number; +} +export interface TransitionOptions { + interrupt: boolean; + tween?: string; +} +export interface Transition { + opacity?: Opacity; + position?: Position; + size?: Size; +} diff --git a/types/openfin/v37/_v2/api/window/window.d.ts b/types/openfin/v37/_v2/api/window/window.d.ts new file mode 100644 index 0000000000..fcefc4fa5d --- /dev/null +++ b/types/openfin/v37/_v2/api/window/window.d.ts @@ -0,0 +1,778 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Bounds from './bounds'; +import { Transition, TransitionOptions } from './transition'; +import { Application } from '../application/application'; +import Transport from '../../transport/transport'; +import { WindowEvents } from '../events/window'; +import { AnchorType } from './anchor-type'; +import { WindowOption } from './windowOption'; +/** + * @lends Window + */ +export default class _WindowModule extends Base { + /** + * Asynchronously returns a Window object that represents an existing window. + * @param { Identity } identity + * @return {Promise.<_Window>} + * @tutorial Window.wrap + * @static + */ + wrap(identity: Identity): Promise<_Window>; + /** + * Synchronously returns a Window object that represents an existing window. + * @param { Identity } identity + * @return {_Window} + * @tutorial Window.wrapSync + * @static + */ + wrapSync(identity: Identity): _Window; + /** + * Creates a new Window. + * @param { WindowOption } options - Window creation options + * @return {Promise.<_Window>} + * @tutorial Window.create + * @static + */ + create(options: WindowOption): Promise<_Window>; + /** + * Asynchronously returns a Window object that represents the current window + * @return {Promise.<_Window>} + * @tutorial Window.getCurrent + * @static + */ + getCurrent(): Promise<_Window>; + /** + * Synchronously returns a Window object that represents the current window + * @return {_Window} + * @tutorial Window.getCurrentSync + * @static + */ + getCurrentSync(): _Window; +} +export interface CloseEventShape { + name: string; + uuid: string; + type: string; + topic: string; +} +export interface WindowInfo { + canNavigateBack: boolean; + canNavigateForward: boolean; + preloadScripts: Array; + title: string; + url: string; +} +export interface FrameInfo { + name: string; + uuid: string; + entityType: string; + parent?: Identity; +} +export interface Area { + height: number; + width: number; + x: number; + y: number; +} +/** + * @typedef { Object } Area + * @property { number } height Area's height + * @property { number } width Area's width + * @property { number } x X coordinate of area's starting point + * @property { number } y Y coordinate of area's starting point + */ +/** + * @typedef {object} Transition + * @property {Opacity} opacity - The Opacity transition + * @property {Position} position - The Position transition + * @property {Size} size - The Size transition +*/ +/** + * @typedef {object} TransitionOptions + * @property {boolean} interrupt - This option interrupts the current animation. When false it pushes +this animation onto the end of the animation queue. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + */ +/** + * @typedef {object} Size + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} width - Optional if height is present. Defaults to the window's current width. + * @property {number} height - Optional if width is present. Defaults to the window's current height. + */ +/** + * @typedef {object} Position + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} left - Defaults to the window's current left position in virtual screen coordinates. + * @property {number} top - Defaults to the window's current top position in virtual screen coordinates. + */ +/** + * @typedef {object} Opacity + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} opacity - This value is clamped from 0.0 to 1.0. +*/ +/** + * Bounds is a interface that has the properties of height, + * width, left, top which are all numbers + * @typedef { Object } Bounds + * @property { number } height Get the application height bound + * @property { number } width Get the application width bound + * @property { number } top Get the application top bound + * @property { number } left Get the application left bound + * @property { number } right Get the application right bound + * @property { number } bottom Get the application bottom bound + */ +/** + * @classdesc A basic window that wraps a native HTML window. Provides more fine-grained + * control over the window state such as the ability to minimize, maximize, restore, etc. + * By default a window does not show upon instantiation; instead the window's show() method + * must be invoked manually. The new window appears in the same process as the parent window. + * @class + * @alias Window +*/ +export declare class _Window extends EmitterBase { + identity: Identity; + /** + * Raised when a window within this application requires credentials from the user. + * + * @event Window#auth-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {object} authInfo + * @property {string} authInfo.host - Host server. + * @property {boolean} authInfo.isProxy - Indicates if the request involves a proxy. + * @property {number} authInfo.port - Port number. + * @property {string} authInfo.realm - Authentication request realm. + * @property {string} authInfo.scheme - Authentication scheme. + */ + /** + * Raised when a window loses focus. + * + * @event Window#blurred + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised after changes in a window's size and/or position. + * + * @event Window#bounds-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when a window has been prevented from closing. A window will be prevented from closing by default, + either through the API or by a user when ‘close-requested’ has been subscribed to and the Window.close(force) flag is false. + * + * @event Window#close-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has closed. + * + * @event Window#closed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has crashed. + * + * @event Window#crashed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when the frame is disabled after all prevent user changes in window's size and/or position have completed. + * + * @event Window#disabled-frame-bounds-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when the frame is disabled during prevented user changes to a window's size and/or position. + * + * @event Window#disabled-frame-bounds-changing + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when the window has been embedded. + * + * @event Window#embedded + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when an external process has exited. + * + * @event Window#external-process-exited + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} processUuid - The process handle UUID. + * @property {number} exitCode - The process exit code + */ + /** + * Raised when an external process has started. + * + * @event Window#external-process-started + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} processUuid - The process handle UUID. + */ + /** + * Raised when a window's frame becomes disabled. + * + * @event Window#frame-disabled + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window's frame becomes enabled. + * + * @event Window#frame-enabled + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window joins/leaves a group and/or when the group a window is a member of changes. + * + * @event Window#group-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} source - Which group array the window that the event listener was registered on is included in: + 'source' The window is included in sourceGroup. + 'target' The window is included in targetGroup. + 'nothing' The window is not included in sourceGroup nor targetGroup. + * @property {string} reason - The reason this event was triggered. + 'leave' A window has left the group due to a leave or merge with group. + 'join' A window has joined the group. + 'merge' Two groups have been merged together. + 'disband' There are no other windows in the group. + * @property {string} name - Name of the window. + * @property {legacyWindowIdentity[]} sourceGroup - All the windows in the group the sourceWindow originated from. + * @property {string} sourceWindowAppUuid - UUID of the application the sourceWindow belongs to the + source window is the window in which (merge/join/leave)group(s) was called. + * @property {string} sourceWindowName - Name of the sourcewindow. + The source window is the window in which (merge/join/leave)group(s) was called. + * @property {legacyWindowIdentity[]} targetGroup - All the windows in the group the targetWindow orginated from. + * @property {string} targetWindowAppUuid - UUID of the application the targetWindow belongs to. + The target window is the window that was passed into (merge/join)group(s). + * @property {string} targetWindowName - Name of the targetWindow. + The target window is the window that was passed into (merge/join)group(s). + */ + /** + * Raised when a window has been hidden. + * + * @event Window#hidden + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} reason - Action prompted the close The reasons are: + "hide" + "hide-on-close" + */ + /** + * Raised when a window is initialized. + * + * @event Window#initialized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window is maximized. + * + * @event Window#maximized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window is minimized. + * + * @event Window#minimized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when window navigation is rejected as per ContentNavigation whitelist/blacklist rules. + * + * @event Window#navigation-rejected + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} sourceName - source of navigation window name. + * @property {string} url - Blocked content url. + */ + /** + * Raised when a window is out of memory. + * + * @event Window#out-of-memory + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised after the execution of all of a window's preload scripts. Contains + information about all window's preload scripts' final states. + * + * @event Window#preload-scripts-state-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states + */ + /** + * Raised during the execution of a window's preload script. Contains information + about a single window's preload script's state, for which the event has been raised. + * + * @event Window#preload-scripts-state-changing + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states + */ + /** + * Raised when an HTTP load was cancelled or failed. + * + * @event Window#resource-load-failed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} errorCode - The Chromium error code. + * @property {string} errorDescription - The Chromium error description. + * @property {string} validatedURL - The url attempted. + * @property {boolean} isMainFrame - Was the attempt made from the main frame. + */ + /** + * Raised when an HTTP resource request has received response details. + * + * @event Window#resource-response-received + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {boolean} status - Status of the request. + * @property {string} newUrl - The URL of the responded resource. + * @property {string} originalUrl - The requested URL. + * @property {number} httpResponseCode - The HTTP Response code. + * @property {string} requestMethod - The HTTP request method. + * @property {string} referrer - The HTTP referrer. + * @property {object} headers - The HTTP headers. + * @property {string} resourceType - Resource type: + "mainFrame", "subFrame", + "styleSheet", "script", "image", + "object", "xhr", or "other" + */ + /** + * Raised when a window has reloaded. + * + * @event Window#reloaded + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} url - Url has has been reloaded. + */ + /** + * Raised when a window is displayed after having been minimized or + when a window leaves the maximize state without minimizing. + * + * @event Window#restored + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has been prevented from showing. + A window will be prevented from showing by default, either through the API or by a user when + ‘show-requested’ has been subscribed to on the window or 'window-show-requested' + on the parent application and the Window.show(force) flag is false. + * + * @event Window#show-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window been shown. + * + * @event Window#shown + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * @typedef {object} legacyWindowIdentity + * @summary Object summary + * @desc Object description + * @property {string} appUuid - The UUID of the application this window entry belongs to. + * @property {string} windowName - The name of this window entry. + */ + /** + * @typedef {object} preloadScriptState + * @summary Object summary + * @desc Object description + * @property {string} url - The url of the preload script. + * @property {string} state - The preload script state: + "load-failed", "failed", "succeeded" + */ + constructor(wire: Transport, identity: Identity); + createWindow(options: WindowOption): Promise<_Window>; + private windowListFromNameList; + /** + * Retrieves an array of frame info objects representing the main frame and any + * iframes that are currently on the page. + * @return {Promise.>} + * @tutorial Window.getAllFrames + */ + getAllFrames(): Promise>; + /** + * Gets the current bounds (top, left, width, height) of the window. + * @return {Promise.} + * @tutorial Window.getBounds + */ + getBounds(): Promise; + /** + * Gives focus to the window. + * @return {Promise.} + * @emits _Window#focused + * @tutorial Window.focus + */ + focus(): Promise; + /** + * Removes focus from the window. + * @return {Promise.} + * @tutorial Window.blur + */ + blur(): Promise; + /** + * Brings the window to the front of the window stack. + * @return {Promise.} + * @tutorial Window.bringToFront + */ + bringToFront(): Promise; + /** + * Performs the specified window transitions. + * @param {Transition} transitions - Describes the animations to perform. See the tutorial. + * @param {TransitionOptions} options - Options for the animation. See the tutorial. + * @return {Promise.} + * @tutorial Window.animate + */ + animate(transitions: Transition, options: TransitionOptions): Promise; + /** + * Hides the window. + * @return {Promise.} + * @tutorial Window.hide + */ + hide(): Promise; + /** + * closes the window application + * @param { boolean } [force = false] Close will be prevented from closing when force is false and + * ‘close-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Window.close + */ + close(force?: boolean): Promise; + /** + * Returns then running applications uuid + * @return {Promise.} + * @tutorial Window.getNativeId + */ + getNativeId(): Promise; + /** + * Prevents a user from changing a window's size/position when using the window's frame. + * @return {Promise.} + * @tutorial Window.disableFrame + */ + disableFrame(): Promise; + /** + * Re-enables user changes to a window's size/position when using the window's frame. + * @return {Promise.} + * @tutorial Window.enableFrame + */ + enableFrame(): Promise; + /** + * Executes Javascript on the window, restricted to windows you own or windows owned by + * applications you have created. + * @param { string } code JavaScript code to be executed on the window. + * @return {Promise.} + * @tutorial Window.executeJavaScript + */ + executeJavaScript(code: string): Promise; + /** + * Flashes the window’s frame and taskbar icon until stopFlashing is called. + * @return {Promise.} + * @tutorial Window.flash + */ + flash(): Promise; + /** + * Stops the taskbar icon from flashing. + * @return {Promise.} + * @tutorial Window.stopFlashing + */ + stopFlashing(): Promise; + /** + * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this + * window. If a window is not in a group an empty array is returned. Please note that + * calling window is included in the result array. + * @return {Promise.>} + * @tutorial Window.getGroup + */ + getGroup(): Promise>; + /** + * Gets an information object for the window. + * @return {Promise.} + * @tutorial Window.getInfo + */ + getInfo(): Promise; + /** + * Gets the current settings of the window. + * @return {Promise.} + * @tutorial Window.getOptions + */ + getOptions(): Promise; + /** + * Gets the parent application. + * @return {Promise.} + * @tutorial Window.getParentApplication + */ + getParentApplication(): Promise; + /** + * Gets the parent window. + * @return {Promise.<_Window>} + * @tutorial Window.getParentWindow + */ + getParentWindow(): Promise<_Window>; + /** + * Gets a base64 encoded PNG snapshot of the window or just part a of it. + * @param { Area } [area] The area of the window to be captured. + * Omitting it will capture the whole visible window. + * @return {Promise.} + * @tutorial Window.getSnapshot + */ + getSnapshot(area?: Area): Promise; + /** + * Gets the current state ("minimized", "maximized", or "restored") of the window. + * @return {Promise.} + * @tutorial Window.getState + */ + getState(): Promise; + /** + * Determines if the window is currently showing. + * @return {Promise.} + * @tutorial Window.isShowing + */ + isShowing(): Promise; + /** + * Joins the same window group as the specified window. + * @param { class } target The window whose group is to be joined + * @return {Promise.} + * @tutorial Window.joinGroup + */ + joinGroup(target: _Window): Promise; + /** + * Reloads the window current page + * @return {Promise.} + * @tutorial Window.reload + */ + reload(ignoreCache?: boolean): Promise; + /** + * Leaves the current window group so that the window can be move independently of those in the group. + * @return {Promise.} + * @tutorial Window.leaveGroup + */ + leaveGroup(): Promise; + /** + * Maximizes the window + * @return {Promise.} + * @tutorial Window.maximize + */ + maximize(): Promise; + /** + * Merges the instance's window group with the same window group as the specified window + * @param { class } target The window whose group is to be merged with + * @return {Promise.} + * @tutorial Window.mergeGroups + */ + mergeGroups(target: _Window): Promise; + /** + * Minimizes the window. + * @return {Promise.} + * @tutorial Window.minimize + */ + minimize(): Promise; + /** + * Moves the window by a specified amount. + * @param { number } deltaLeft The change in the left position of the window + * @param { number } deltaTop The change in the top position of the window + * @return {Promise.} + * @tutorial Window.moveBy + */ + moveBy(deltaLeft: number, deltaTop: number): Promise; + /** + * Moves the window to a specified location. + * @param { number } left The left position of the window + * @param { number } top The top position of the window + * @return {Promise.} + * @tutorial Window.moveTo + */ + moveTo(left: number, top: number): Promise; + /** + * Resizes the window by a specified amount. + * @param { number } deltaWidth The change in the width of the window + * @param { number } deltaHeight The change in the height of the window + * @param { AnchorType } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right". + * If undefined, the default is "top-left" + * @return {Promise.} + * @tutorial Window.resizeBy + */ + resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType): Promise; + /** + * Resizes the window to the specified dimensions. + * @param { number } width The change in the width of the window + * @param { number } height The change in the height of the window + * @param { AnchorType } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right". + * If undefined, the default is "top-left" + * @return {Promise.} + * @tutorial Window.resizeTo + */ + resizeTo(width: number, height: number, anchor: AnchorType): Promise; + /** + * Restores the window to its normal state (i.e., unminimized, unmaximized). + * @return {Promise.} + * @tutorial Window.restore + */ + restore(): Promise; + /** + * Will bring the window to the front of the entire stack and give it focus. + * @return {Promise.} + * @tutorial Window.setAsForeground + */ + setAsForeground(): Promise; + /** + * Sets the window's size and position. + * @property { Bounds } bounds This is a * @type {string} name - name of the window.object that holds the propertys of + * @return {Promise.} + * @tutorial Window.setBounds + */ + setBounds(bounds: Bounds): Promise; + /** + * Shows the window if it is hidden. + * @param { boolean } [force = false] Show will be prevented from showing when force is false and + * ‘show-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Window.show + */ + show(force?: boolean): Promise; + /** + * Shows the window if it is hidden at the specified location. + * If the toggle parameter is set to true, the window will + * alternate between showing and hiding. + * @param { number } left The left position of the window + * @param { number } top The right position of the window + * @param { boolean } force Show will be prevented from closing when force is false and + * ‘show-requested’ has been subscribed to for application’s main window + * @return {Promise.} + * @tutorial Window.showAt + */ + showAt(left: number, top: number, force?: boolean): Promise; + /** + * Shows the Chromium Developer Tools + * @return {Promise.} + * @tutorial Window.showDeveloperTools + */ + showDeveloperTools(): Promise; + /** + * Updates the window using the passed options + * @param {*} options Changes a window's options that were defined upon creation. See tutorial + * @return {Promise.} + * @tutorial Window.updateOptions + */ + updateOptions(options: any): Promise; + /** + * Provides credentials to authentication requests + * @param { string } userName userName to provide to the authentication challange + * @param { string } password password to provide to the authentication challange + * @return {Promise.} + * @tutorial Window.authenticate + */ + authenticate(userName: string, password: string): Promise; + /** + * Returns the zoom level of the window. + * @return {Promise.} + * @tutorial Window.getZoomLevel + */ + getZoomLevel(): Promise; + /** + * Sets the zoom level of the window. + * @param { number } level The zoom level + * @return {Promise.} + * @tutorial Window.setZoomLevel + */ + setZoomLevel(level: number): Promise; + /** + * Navigates the window to a specified URL. + * @param {string} url - The URL to navigate the window to. + * @return {Promise.} + * @tutorial Window.navigate + */ + navigate(url: string): Promise; + /** + * Navigates the window back one page. + * @return {Promise.} + * @tutorial Window.navigateBack + */ + navigateBack(): Promise; + /** + * Stops any current navigation the window is performing. + * @return {Promise.} + * @tutorial Window.stopNavigation + */ + stopNavigation(): Promise; +} diff --git a/types/openfin/v37/_v2/api/window/windowOption.d.ts b/types/openfin/v37/_v2/api/window/windowOption.d.ts new file mode 100644 index 0000000000..faab275187 --- /dev/null +++ b/types/openfin/v37/_v2/api/window/windowOption.d.ts @@ -0,0 +1,46 @@ +import { DownloadPreloadOption } from '../system/download-preload'; +export interface WindowOption { + accelerator?: object; + alwaysOnTop?: boolean; + api?: object; + aspectRatio?: number; + autoShow?: boolean; + backgroundColor?: string; + contentNavigation?: object; + contextMenu?: boolean; + cornerRounding?: object; + customData?: string; + customRequestHeaders?: Array; + defaultCentered?: boolean; + defaultHeight?: number; + defaultLeft?: number; + defaultTop?: number; + defaultWidth?: number; + frame?: boolean; + hideOnClose?: boolean; + icon?: string; + maxHeight?: number; + maximizable?: boolean; + maxWidth?: number; + minHeight?: number; + minimizable?: boolean; + minWidth?: number; + name?: string; + opacity?: number; + preloadScripts?: Array; + resizable?: boolean; + resizeRegion?: object; + saveWindowState?: boolean; + shadow?: boolean; + showTaskbarIcon?: boolean; + smallWindow?: boolean; + state?: string; + taskbarIconGroup?: string; + url?: string; + uuid?: string; + waitForPageLoad?: boolean; +} +export interface CustomRequestHeaders { + urlPatterns: Array; + headers: Array; +} diff --git a/types/openfin/v37/_v2/environment/environment.d.ts b/types/openfin/v37/_v2/environment/environment.d.ts new file mode 100644 index 0000000000..0b0f1571f2 --- /dev/null +++ b/types/openfin/v37/_v2/environment/environment.d.ts @@ -0,0 +1,10 @@ +import { NewConnectConfig } from '../transport/wire'; +export interface Environment { + writeToken(path: string, token: string): Promise; + retrievePort(config: NewConnectConfig): Promise; + getNextMessageId(): any; + getRandomId(): string; + createChildWindow(options: any): Promise; + isWindowExists(uuid: string, name: string): boolean; +} +export declare const notImplementedEnvErrorMsg = "Not implemented in this environment"; diff --git a/types/openfin/v37/_v2/environment/node-env.d.ts b/types/openfin/v37/_v2/environment/node-env.d.ts new file mode 100644 index 0000000000..03e0faeede --- /dev/null +++ b/types/openfin/v37/_v2/environment/node-env.d.ts @@ -0,0 +1,11 @@ +import { Environment } from './environment'; +import { NewConnectConfig } from '../transport/wire'; +export default class NodeEnvironment implements Environment { + private messageCounter; + writeToken: (path: string, token: string) => Promise; + retrievePort: (config: NewConnectConfig) => Promise; + getNextMessageId: () => any; + createChildWindow: (options: any) => Promise; + getRandomId: () => string; + isWindowExists: (uuid: string, name: string) => boolean; +} diff --git a/types/openfin/v37/_v2/environment/openfin-env.d.ts b/types/openfin/v37/_v2/environment/openfin-env.d.ts new file mode 100644 index 0000000000..456e2f8caf --- /dev/null +++ b/types/openfin/v37/_v2/environment/openfin-env.d.ts @@ -0,0 +1,11 @@ +import { Environment } from './environment'; +import { NewConnectConfig } from '../transport/wire'; +export default class OpenFinEnvironment implements Environment { + writeToken: (path: string, token: string) => Promise; + retrievePort: (config: NewConnectConfig) => Promise; + getNextMessageId: () => any; + createChildWindow: (options: any) => Promise; + getRandomId: () => string; + private resolveUrl; + isWindowExists: (uuid: string, name: string) => boolean; +} diff --git a/types/openfin/v37/_v2/environment/openfin-renderer-api.d.ts b/types/openfin/v37/_v2/environment/openfin-renderer-api.d.ts new file mode 100644 index 0000000000..82822c3111 --- /dev/null +++ b/types/openfin/v37/_v2/environment/openfin-renderer-api.d.ts @@ -0,0 +1,6 @@ +export declare const ipc: any; +export declare const routingId: any; +export declare const CORE_MESSAGE_CHANNEL: any; +export declare const outboundTopic = "of-window-message"; +export declare const inboundTopic: string; +export declare const currentWindowIdentity: any; diff --git a/types/openfin/v37/_v2/identity.d.ts b/types/openfin/v37/_v2/identity.d.ts new file mode 100644 index 0000000000..f10f030248 --- /dev/null +++ b/types/openfin/v37/_v2/identity.d.ts @@ -0,0 +1,4 @@ +export interface Identity { + uuid: string; + name?: string; +} diff --git a/types/openfin/v37/_v2/launcher/launcher.d.ts b/types/openfin/v37/_v2/launcher/launcher.d.ts new file mode 100644 index 0000000000..d0ffc16989 --- /dev/null +++ b/types/openfin/v37/_v2/launcher/launcher.d.ts @@ -0,0 +1,15 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export default class Launcher { + private os; + OpenFin_Installer: string; + Installer_Work_Dir: string; + Security_Realm_Config_Key: string; + nixConfig?: any; + constructor(); + launch(config: ConfigWithRuntime, manifestLocation: string, namedPipeName: string): Promise; + static IS_SUPPORTED(): boolean; + private macLaunch; + private winLaunch; +} diff --git a/types/openfin/v37/_v2/launcher/nix-launch.d.ts b/types/openfin/v37/_v2/launcher/nix-launch.d.ts new file mode 100644 index 0000000000..02b0da4fbb --- /dev/null +++ b/types/openfin/v37/_v2/launcher/nix-launch.d.ts @@ -0,0 +1,14 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export declare function getUrl(version: string, urlPath: string): string; +export declare function download(version: string, folder: string, osConfig: OsConfig): Promise; +export declare function getRuntimePath(version: string): Promise; +export declare function install(versionOrChannel: string, osConfig: OsConfig): Promise; +export interface OsConfig { + manifestLocation: string; + namedPipeName: string; + urlPath: string; + executablePath: string; +} +export default function launch(config: ConfigWithRuntime, osConfig: OsConfig): Promise; diff --git a/types/openfin/v37/_v2/launcher/util.d.ts b/types/openfin/v37/_v2/launcher/util.d.ts new file mode 100644 index 0000000000..808ad015ea --- /dev/null +++ b/types/openfin/v37/_v2/launcher/util.d.ts @@ -0,0 +1,8 @@ +export declare function exists(path: string): Promise; +export declare function get(url: string): Promise; +export declare function unzip(file: string, dest: string): Promise; +export declare function rmDir(dirPath: string, removeSelf?: boolean): Promise; +export declare function downloadFile(url: string, writeLocation: string): Promise<{}>; +export declare function resolveRuntimeVersion(versionOrChannel: string): Promise; +export declare function first(arr: T[], func: (x: T, i: number, r: T[]) => boolean): T | null; +export declare function resolveDir(base: string, paths: string[]): Promise; diff --git a/types/openfin/v37/_v2/launcher/win-launch.d.ts b/types/openfin/v37/_v2/launcher/win-launch.d.ts new file mode 100644 index 0000000000..b08fac3f8a --- /dev/null +++ b/types/openfin/v37/_v2/launcher/win-launch.d.ts @@ -0,0 +1,4 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export default function launch(config: ConfigWithRuntime, manifestLocation: string, namedPipeName: string, Installer_Work_Dir: string): Promise; diff --git a/types/openfin/v37/_v2/main.d.ts b/types/openfin/v37/_v2/main.d.ts new file mode 100644 index 0000000000..2f4a3d8730 --- /dev/null +++ b/types/openfin/v37/_v2/main.d.ts @@ -0,0 +1,11 @@ +import Fin from './api/fin'; +import { Application } from './api/application/application'; +import { _Window as Window } from './api/window/window'; +import { _Frame as Frame } from './api/frame/frame'; +import { _Notification as Notification } from './api/notification/notification'; +import System from './api/system/system'; +import { ConnectConfig } from './transport/wire'; +export declare function connect(config: ConnectConfig): Promise; +export declare function launch(config: ConnectConfig): Promise; +export { Identity } from './identity'; +export { Fin, Application, Window, System, Frame, Notification }; diff --git a/types/openfin/v37/_v2/of-main.d.ts b/types/openfin/v37/_v2/of-main.d.ts new file mode 100644 index 0000000000..cb0ff5c3b5 --- /dev/null +++ b/types/openfin/v37/_v2/of-main.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/types/openfin/v37/_v2/transport/elipc.d.ts b/types/openfin/v37/_v2/transport/elipc.d.ts new file mode 100644 index 0000000000..94c398cba5 --- /dev/null +++ b/types/openfin/v37/_v2/transport/elipc.d.ts @@ -0,0 +1,13 @@ +/// +import { EventEmitter } from 'events'; +import { Wire, READY_STATE } from './wire'; +export default class ElIPCTransport extends EventEmitter implements Wire { + protected wire: any; + onmessage: (data: any) => void; + constructor(onmessage: (data: any) => void); + connectSync: () => any; + connect: (address: string) => Promise; + send(data: any, flags?: any): Promise; + shutdown(): Promise; + static READY_STATE: typeof READY_STATE; +} diff --git a/types/openfin/v37/_v2/transport/port-discovery.d.ts b/types/openfin/v37/_v2/transport/port-discovery.d.ts new file mode 100644 index 0000000000..d8ea25934d --- /dev/null +++ b/types/openfin/v37/_v2/transport/port-discovery.d.ts @@ -0,0 +1,17 @@ +import { PortDiscoveryConfig } from './wire'; +import { Environment } from '../environment/environment'; +export declare class PortDiscovery { + private savedConfig; + private namedPipeName; + private manifestLocation; + private namedPipeServer; + private pipeConnection; + private timeoutTimer; + private environment; + constructor(config: PortDiscoveryConfig, environment: Environment); + retrievePort(): Promise; + private createDiscoveryNamedPipe; + private listenDiscoveryMessage; + private createManifest; + private cleanup; +} diff --git a/types/openfin/v37/_v2/transport/transport-errors.d.ts b/types/openfin/v37/_v2/transport/transport-errors.d.ts new file mode 100644 index 0000000000..90f9d10f55 --- /dev/null +++ b/types/openfin/v37/_v2/transport/transport-errors.d.ts @@ -0,0 +1,17 @@ +export declare class DisconnectedError extends Error { + constructor(readyState: number); + readyState: number; +} +export declare class UnexpectedActionError extends Error { +} +export declare class DuplicateCorrelationError extends Error { +} +export declare class NoAckError extends Error { +} +export declare class NotImplementedError extends Error { +} +export declare class NotSupportedError extends Error { +} +export declare class RuntimeError extends Error { + constructor(data: any); +} diff --git a/types/openfin/v37/_v2/transport/transport.d.ts b/types/openfin/v37/_v2/transport/transport.d.ts new file mode 100644 index 0000000000..519562de95 --- /dev/null +++ b/types/openfin/v37/_v2/transport/transport.d.ts @@ -0,0 +1,65 @@ +/// +import { Wire, WireConstructor, READY_STATE, ExistingConnectConfig, ConnectConfig, InternalConnectConfig } from './wire'; +import { Identity } from '../identity'; +import { EventEmitter } from 'events'; +import { Environment } from '../environment/environment'; +import { RuntimeEvent } from '../api/events/base'; +import { EventAggregator } from '../api/events/eventAggregator'; +export declare type MessageHandler = (data: any) => boolean; +declare class Transport extends EventEmitter { + protected wireListeners: Map; + protected uncorrelatedListener: Function; + me: Identity; + protected wire: Wire; + environment: Environment; + topicRefMap: Map; + sendRaw: Wire['send']; + eventAggregator: EventAggregator; + protected messageHandlers: MessageHandler[]; + constructor(wireType: WireConstructor, environment: Environment); + connectSync: (config: ConnectConfig) => any; + connect(config: InternalConnectConfig): Promise; + connectByPort(config: ExistingConnectConfig): Promise; + READY_STATE: typeof READY_STATE; + ferryAction(data: any): Promise>; + registerMessageHandler(handler: MessageHandler): void; + protected addWireListener(id: number, resolve: Function, reject: Function, uncorrelated: boolean): void; + protected onmessage(data: Message): void; + protected handleMessage(data: Message): boolean; +} +export default Transport; +interface Transport { + sendAction(action: 'request-external-authorization', payload: {}, uncorrelated: true): Promise>; + sendAction(action: string, payload: {}, uncorrelated: boolean): Promise>; + topicRefMap: Map; +} +export declare class Message { + action: string; + payload: T; + correlationId?: number; +} +export declare class EventMessage implements Message { + action: 'process-desktop-event'; + payload: RuntimeEvent; +} +export declare class NotificationEventMessage implements Message { + action: 'process-notification-event'; + payload: NotificationEvent; +} +export interface NotificationEvent { + payload: { + notificationId: string; + }; + type: string | symbol; +} +export declare class Payload { + success: boolean; + data: any; +} +export declare class AuthorizationPayload { + token: string; + file: string; +} diff --git a/types/openfin/v37/_v2/transport/websocket.d.ts b/types/openfin/v37/_v2/transport/websocket.d.ts new file mode 100644 index 0000000000..5617afa8e3 --- /dev/null +++ b/types/openfin/v37/_v2/transport/websocket.d.ts @@ -0,0 +1,14 @@ +/// +import { EventEmitter } from 'events'; +import * as WebSocket from 'ws'; +import { Wire, READY_STATE } from './wire'; +export default class WebSocketTransport extends EventEmitter implements Wire { + protected wire: WebSocket; + onmessage: (data: any) => void; + constructor(onmessage: (data: any) => void); + connect: (address: string) => Promise; + connectSync: () => any; + send(data: any, flags?: any): Promise; + shutdown(): Promise; + static READY_STATE: typeof READY_STATE; +} diff --git a/types/openfin/v37/_v2/transport/wire.d.ts b/types/openfin/v37/_v2/transport/wire.d.ts new file mode 100644 index 0000000000..227c6d4d72 --- /dev/null +++ b/types/openfin/v37/_v2/transport/wire.d.ts @@ -0,0 +1,71 @@ +/// +import { EventEmitter } from 'events'; +export interface Wire extends EventEmitter { + connect(address: string): Promise; + connectSync(): any; + send(data: any): Promise; + shutdown(): Promise; +} +export interface WireConstructor { + new (onmessage: (data: any) => void): Wire; +} +export interface RuntimeConfig { + version: string; + fallbackVersion?: string; + securityRealm?: string; + verboseLogging?: boolean; + arguments?: string; + rvmDir?: string; +} +export interface BaseConfig { + uuid?: string; + address?: string; + name?: string; + nonPersistent?: boolean; + runtimeClient?: boolean; + licenseKey?: string; + client?: any; + manifestUrl?: string; + startupApp?: any; + lrsUrl?: string; + assetsUrl?: string; + devToolsPort?: number; + installerUI?: boolean; + runtime?: RuntimeConfig; + appAssets?: [{ + src: string; + alias: string; + target: string; + version: string; + args: string; + }]; + customItems?: [any]; + timeout?: number; +} +export interface ConfigWithUuid extends BaseConfig { + uuid: string; +} +export interface ExistingConnectConfig extends ConfigWithUuid { + address: string; +} +export interface ConfigWithRuntime extends BaseConfig { + runtime: RuntimeConfig; +} +export interface ExternalConfig extends BaseConfig { + manifestUrl: string; +} +export declare type NewConnectConfig = ConfigWithUuid & ConfigWithRuntime; +export declare type PortDiscoveryConfig = (ExternalConfig & ConfigWithRuntime) | NewConnectConfig; +export declare type ConnectConfig = ExistingConnectConfig | NewConnectConfig | ExternalConfig; +export declare type InternalConnectConfig = ExistingConnectConfig | NewConnectConfig; +export declare function isExternalConfig(config: ConnectConfig): config is ExternalConfig; +export declare function isExistingConnectConfig(config: any): config is ExistingConnectConfig; +export declare function isNewConnectConfig(config: any): config is NewConnectConfig; +export declare function isPortDiscoveryConfig(config: any): config is PortDiscoveryConfig; +export declare function isInternalConnectConfig(config: any): config is InternalConnectConfig; +export declare enum READY_STATE { + CONNECTING = 0, + OPEN = 1, + CLOSING = 2, + CLOSED = 3 +} diff --git a/types/openfin/v37/_v2/util/normalize-config.d.ts b/types/openfin/v37/_v2/util/normalize-config.d.ts new file mode 100644 index 0000000000..ed322d30ec --- /dev/null +++ b/types/openfin/v37/_v2/util/normalize-config.d.ts @@ -0,0 +1,3 @@ +import { ConnectConfig, InternalConnectConfig, ExternalConfig } from '../transport/wire'; +export declare function normalizeConfig(config: ConnectConfig): Promise; +export declare function validateConfig(config: ConnectConfig): Promise; diff --git a/types/openfin/v37/_v2/util/promises.d.ts b/types/openfin/v37/_v2/util/promises.d.ts new file mode 100644 index 0000000000..8e7bf9efe9 --- /dev/null +++ b/types/openfin/v37/_v2/util/promises.d.ts @@ -0,0 +1,5 @@ +export declare function promisify(func: Function): (...args: any[]) => Promise; +export declare function promiseMap(arr: T[], asyncF: (x: T, i: number, r: T[]) => Promise): Promise; +export declare type asyncF = (...args: any[]) => Promise; +export declare function serial(arr: asyncF[]): Promise; +export declare function promiseMapSerial(arr: any[], func: asyncF): Promise; diff --git a/types/openfin/v37/_v2/util/ref-counter.d.ts b/types/openfin/v37/_v2/util/ref-counter.d.ts new file mode 100644 index 0000000000..8184e09079 --- /dev/null +++ b/types/openfin/v37/_v2/util/ref-counter.d.ts @@ -0,0 +1,7 @@ +export default class RefCoutner { + topicRefMap: Map; + incRefCount(key: string): number; + decRefCount(key: string): number; + actOnFirst(key: string, firstAction: () => any, nonFirstAction?: () => void): any; + actOnLast(key: string, lastAction: () => any, nonLastAction?: () => void): any; +} diff --git a/types/openfin/v37/index.d.ts b/types/openfin/v37/index.d.ts new file mode 100644 index 0000000000..b5d04f1a27 --- /dev/null +++ b/types/openfin/v37/index.d.ts @@ -0,0 +1,1304 @@ +// Type definitions for OpenFin API 37.0 +// Project: https://openfin.co/ +// Definitions by: Chris Barker +// Ricardo de Pena +// Roma +// Li Cui +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +// based on v9.61.37.14 +// see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean + +/** + * JavaScript API + * The JavaScript API allows you to create an HTML/JavaScript application that has access to the native windowing environment, + * can communicate with other applications and has access to sandboxed system-level features. + * + * API Ready + * When using the OpenFin API, it is important to ensure that it has been fully loaded before making any API calls. To verify + * that the API is in fact ready, be sure to make any API calls either from within the fin.desktop.main() method or explicitly + * after it has returned. This avoids the situation of trying to access methods that are not yet fully injected. + * + * Overview + * When running within the OpenFin Runtime your web applications have access to the "fin" namespace and all the modules within the API + * without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "documennt" objects. + */ +declare namespace fin { + var Application: import('./_v2/api/application/application').default; + var Clipboard: import('./_v2/api/clipboard/clipboard').default; + var ExternalApplication: import('./_v2/api/external-application/external-application').default + var Frame: import('./_v2/api/frame/frame').default; + var GlobalHotkey: import('./_v2/api/global-hotkey/index').default; + var InterApplicationBus: import('./_v2/api/interappbus/interappbus').default; + var Notification: import('./_v2/api/notification/notification').default; + var System: import('./_v2/api/system/system').default; + var Window: import('./_v2/api/window/window').default; + + // v2 shapes + type Identity = import('./_v2/identity').Identity; + type LaunchInfo = import('./_v2/api/application/application').ApplicationInfo; + type ShortCutConfig = import('./_v2/api/application/application').ShortCutConfig; + type TrayInfo = import('./_v2/api/application/application').TrayInfo; + type ApplicationOption = import('./_v2/api/application/applicationOption').ApplicationOption; + type ExternalApplicationInfo = import('./_v2/api/external-application/external-application').ExternalApplicationInfo; + type ApplicationInfo = import('./_v2/api/system/application').ApplicationInfo; + type ClearCacheOption = import('./_v2/api/system/clearCacheOption').ClearCacheOption; + type CookieInfo = import('./_v2/api/system/cookie').CookieInfo; + type CookieOption = import('./_v2/api/system/cookie').CookieOption; + type AppAssetInfo = import('./_v2/api/system/download-asset').AppAssetInfo; + type AppAssetRequest = import('./_v2/api/system/download-asset').AppAssetRequest; + type RuntimeDownloadOptions = import('./_v2/api/system/download-asset').RuntimeDownloadOptions; + type RuntimeDownloadProgress = import('./_v2/api/system/download-asset').RuntimeDownloadProgress; + type DownloadPreloadInfo = import('./_v2/api/system/download-preload').DownloadPreloadInfo; + type DownloadPreloadOption = import('./_v2/api/system/download-preload').DownloadPreloadOption; + type EntityInfo = import('./_v2/api/system/entity').EntityInfo; + type ExternalProcessRequestType = import('./_v2/api/system/external-process').ExternalProcessRequestType; + type ExternalProcessInfo = import('./_v2/api/system/external-process').ExternalProcessInfo; + type HostSpecs = import('./_v2/api/system/host-specs').HostSpecs; + type LogInfo = import('./_v2/api/system/log').LogInfo; + type MonitorInfo = import('./_v2/api/system/monitor').MonitorInfo; + type PointTopLeft = import('./_v2/api/system/point').PointTopLeft; + type ProcessInfo = import('./_v2/api/system/process').ProcessInfo; + type ProxyInfo = import('./_v2/api/system/proxy').ProxyInfo; + type RegistryInfo = import('./_v2/api/system/registry-info').RegistryInfo; + type RuntimeInfo = import('./_v2/api/system/runtime-info').RuntimeInfo; + type RVMInfo = import('./_v2/api/system/rvm').RVMInfo; + type WindowDetail = import('./_v2/api/system/window').WindowDetail; + type WindowInfo = import('./_v2/api/system/window').WindowInfo; + type AnchorType = import('./_v2/api/window/anchor-type').AnchorType; + type Bounds = import('./_v2/api/window/bounds').default; + type Transition = import('./_v2/api/window/transition').Transition; + type TransitionOptions = import('./_v2/api/window/transition').TransitionOptions; + type WindowOption = import('./_v2/api/window/windowOption').WindowOption; + + const desktop: OpenFinDesktop; + + interface OpenFinDesktop { + main(f: () => any): void; + Application: OpenFinApplicationStatic; + ExternalApp: OpenFinExternalApplicationStatic; + GlobalHotkey: OpenFinGlobalHotkey; + InterApplicationBus: OpenFinInterApplicationBus; + Notification: OpenFinNotificationStatic; + System: OpenFinSystem; + Window: OpenFinWindowStatic; + Frame: OpenFinFrameStatic; + } + + interface OpenFinApplicationStatic { + /** + * Creates a new Application. + * An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events. + */ + new ( + options: ApplicationOption, + callback?: (successObj: { httpResponseCode: number }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication; + /** + * Launches the given Application manifest. + */ + createFromManifest(manifestUrl: string, callback?: (app: OpenFinApplication) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Returns an Application object that represents an existing application. + */ + getCurrent(): OpenFinApplication; + /** + * Returns an Application object that represents an existing application. + */ + wrap(uuid: string): OpenFinApplication; + } + + /** + * Application + * An object representing an application.Allows the developer to create, execute, show / close an application as well as listen to application events. + */ + interface OpenFinApplication { + /** + * Returns an instance of the main Window of the application + */ + getWindow(): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinApplicationEventType, + listener: (event: ApplicationBaseEvent + | TrayIconClickedEvent + | WindowEvent + | WindowAlertRequestedEvent + | WindowAuthRequested + | WindowNavigationRejectedEvent + | WindowEndLoadEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Closes the application and any child windows created by the application. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of wrapped fin.desktop.Windows for each of the application's child windows. + */ + getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows. + */ + getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest. + */ + getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest. + */ + getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves current configuration of application's shortcuts. + */ + getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves information about the application. + */ + getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves information about the system tray. + */ + getTrayIconInfo(callback?: (trayInfo: TrayInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the application is currently running. + */ + isRunning(callback?: (running: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Registers a username and an app name for licensing purposes. + */ + registerUser(userName: string, appName: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinApplicationEventType, + previouslyRegisteredListener: (event: ApplicationBaseEvent + | TrayIconClickedEvent + | WindowEvent + | WindowAlertRequestedEvent + | WindowAuthRequested + | WindowNavigationRejectedEvent + | WindowEndLoadEvent) => any, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Removes the application's icon from the tray. + */ + removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restarts the application. + */ + restart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Runs the application. When the application is created, run must be called. + */ + run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * Tells the rvm to relaunch the main application once upon a complete shutdown + */ + scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets new shortcut configuration for current application. + * Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to + * be able to change shortcut states. + */ + setShortcuts(config: ShortCutConfig, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Adds a customizable icon in the system tray and notifies the application when clicked. + */ + setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the application by terminating its process. + */ + terminate(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Waits for a hanging application. This method can be called in response to an application "not-responding" to allow the application + * to continue and to generate another "not-responding" message after a certain period of time. + */ + wait(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * The Application's uuid + */ + uuid: string; + } + + interface SuccessObj { + httpResponseCode: number; + } + + interface NetworkErrorInfo extends ErrorInfo { + networkErrorCode: number; + } + + interface ErrorInfo { + stack: string; + message: string; + } + + /** + * Clipboard + * Clipboard API allows reading and writting to the clipboard in multiple formats. + */ + interface OpenFinClipboard { + /** + * Reads available formats for the clipboard type + */ + availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Reads available formats for the clipboard type + */ + readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as Rtf + */ + readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as plain text + */ + readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard + */ + write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Html + */ + writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Rtf + */ + writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as plain text + */ + writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + interface OpenFinExternalApplicationStatic { + /** + * Returns an External Application object that represents an existing external application. + */ + wrap(uuid: string): OpenFinExternalApplication; + } + /** + * ExternalApplication + * An object representing an application. Allows the developer to create, execute, show and close an application, as well as listen to application events. + */ + interface OpenFinExternalApplication { + /** + * Retrieves information about the application. + */ + getInfo(callback?: (info: ExternalApplicationInfo) => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinExternalApplicationEventType, + listener: () => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinExternalApplicationEventType, + listener: () => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + /** + * GlobalHotkey + * The Global Hotkey allows the registration and unregistration of given hotkeys at the OS level, meaning a Window/Application will receive the events regardless of focused state. + */ + interface OpenFinGlobalHotkey { + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinGlobalHotkeyEventType, + listener: (event: GlobalHotkeyEvent) => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Checks if a given hotkey has been registered + */ + isRegistered(hotkey: string, callback?: (registered: boolean) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Registers a global hotkey with the operating system. + */ + register(hotkey: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinGlobalHotkeyEventType, + listener: (event: GlobalHotkeyEvent) => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Unregisters a global hotkey with the operating system. + */ + unregister(hotkey: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Unregisters all global hotkeys for the current application. + */ + unregisterAll(callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + /** + * InterApplicationBus + * A messaging bus that allows for pub/sub messaging between different applications. + */ + interface OpenFinInterApplicationBus { + /** + * Adds a listener that gets called when applications subscribe to the current application's messages. + */ + addSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Adds a listener that gets called when applications unsubscribe to the current application's messages. + */ + addUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered subscribe listener. + */ + removeSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered unsubscribe listener. + */ + removeUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Publishes a message to all applications running on OpenFin Runtime that are subscribed to the specified topic. + */ + publish(topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sends a message to a specific application on a specific topic. + */ + send(destinationUuid: string, name: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + send(destinationUuid: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Subscribes to messages from the specified application on the specified topic. If the subscription is for a uuid, [name], + * topic combination that has already been published to upon subscription you will receive the last 20 missed messages in the order they were published. + */ + subscribe( + senderUuid: string, + name: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + subscribe( + senderUuid: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Unsubscribes to messages from the specified application on the specified topic. + */ + unsubscribe( + senderUuid: string, + name: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + unsubscribe( + senderUuid: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + } + + interface OpenFinNotificationStatic { + /** + * ctor + */ + new (options: NotificationOptions, callback?: () => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinNotification; + /** + * Gets an instance of the current notification. For use within a notification window to close the window or send a message back to its parent application. + */ + getCurrent(): OpenFinNotification; + } + + /** + * Notification + * Notification represents a window on OpenFin Runtime which is shown briefly to the user on the bottom-right corner of the primary monitor. + * A notification is typically used to alert the user of some important event which requires his or her attention. + * Notifications are a child or your application that are controlled by the runtime. + */ + interface OpenFinNotification { + /** + * Closes the notification. + */ + close(callback?: () => void): void; + /** + * Sends a message to the notification. + */ + sendMessage(message: any, callback?: () => void): void; + /** + * Sends a message from the notification to the application that created the notification. The message is handled by the notification's onMessage callback. + */ + sendMessageToApplication(message: any, callback?: () => void): void; + } + + interface NotificationOptions { + /** + * A boolean that will force dismissal even if the mouse is hovering over the notification + */ + ignoreMouseOver?: boolean; + /** + * A message of any primitive or composite-primitive type to be passed to the notification upon creation. + */ + message?: any; + /** + * The timeout for displaying a notification.Can be in milliseconds or "never". + */ + timeout?: number | "never"; + /** + * The url of the notification + */ + url?: string; + /** + * A function that is called when a notification is clicked. + */ + onClick?(callback: () => void): void; + /** + * Invoked when the notification is closed via .close() method on the created notification instance + * or the by the notification itself via fin.desktop.Notification.getCurrent().close(). + * NOTE: this is not invoked when the notification is dismissed via a swipe. For the swipe dismissal callback see onDismiss + */ + onClose?(callback: () => void): void; + /** + * Invoked when a the notification is dismissed by swiping it off the screen to the right. NOTE: this is no fired on a programmatic close. + */ + onDismiss?(callback: () => void): void; + /** + * A function that is called when an error occurs.The reason for the error is passed as an argument. + */ + onError?(errorCallback: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * The onMessage function will respond to messages sent from notification.sendMessageToApplication. + * The function is passed the message, which can be of any primitive or composite-primitive type. + */ + onMessage?(callback: (message: any) => void): void; + /** + * A function that is called when a notification is shown. + */ + onShow?(callback: (successObj: SuccessObj) => void): void; + } + + /** + * System + * An object representing the core of OpenFin Runtime. + * Allows the developer to perform system-level actions, such as accessing logs, viewing processes, clearing the cache and exiting the runtime. + */ + interface OpenFinSystem { + Clipboard: OpenFinClipboard; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinSystemEventType, + listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Clears cached data containing window state/positions, + * application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage. + */ + clearCache(options: ClearCacheOption, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Clears all cached data when OpenFin Runtime exits. + */ + deleteCacheOnExit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Downloads the given application asset + */ + downloadAsset( + assetObj: AppAssetInfo, + progressListener?: (progress: { downloadedBytes: number, totalBytes: number }) => void, + callback?: (successObj: { path: string }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + + /** + * Download preload scripts from given URLs + */ + downloadPreloadScripts(scripts: DownloadPreloadOption[], callback?: (downloadInfo: DownloadPreloadInfo[]) => void, + errorCallback?: (reason: string) => void): void; + /** + * Downloads the given OpenFin Runtime. + */ + downloadRuntime(options: RuntimeDownloadOptions, onProgress?: (progress: RuntimeDownloadProgress) => void, onComplete?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Exits the Runtime. + */ + exit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Writes any unwritten cookies data to disk. + */ + flushCookieStore(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all applications. + */ + getAllApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all external applications. + */ + getAllExternalApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + */ + getAllWindows(callback?: (windowInfoList: WindowInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the app asset. + */ + getAppAssetInfo(options: AppAssetRequest, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Get additional info of cookies. + */ + getCookies(option: CookieOption, callback?: (info: CookieInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + */ + getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the configuration object that started the OpenFin Runtime. + */ + getDeviceId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns a hex encoded hash of the mac address and the currently logged in user name + */ + getDeviceUserId(callback?: (id: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns an Entity info object relating to the entity specified by the uuid and name passed in. The possible types are 'window', 'iframe', 'external connection' or 'unknown'. + */ + getEntityInfo(uuid: string, name: string, callback?: (info: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the value of a given environment variable on the computer on which the runtime is installed. + */ + getEnvironmentVariable(envVar: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves currently focused window identity. + */ + getFocusedWindow(callback?: (focusedWindowIdentity: Identity) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves system information. + */ + getHostSpecs(callback?: (info: HostSpecs) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the contents of the log with the specified filename. + */ + getLog(logFileName: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing information for each log file. + */ + getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the minimum (inclusive) logging level that is currently being written to the logs. + */ + getMinLogLevel(callback?: (logLevel: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an object that contains data about the about the monitor setup of the computer that the runtime is running on. + */ + getMonitorInfo(callback?: (monitorInfo: MonitorInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the mouse in virtual screen coordinates (left, top). + */ + getMousePosition(callback?: (mousePosition: PointTopLeft) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of all of the runtime processes that are currently running. + * Each element in the array is an object containing the uuid and the name of the application to which the process belongs. + */ + getProcessList(callback?: (processInfoList: ProcessInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the Proxy settings. + */ + getProxySettings(callback?: (proxy: ProxyInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the running Runtime in an object. + */ + getRuntimeInfo(callback?: (rvmInfo: RuntimeInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the running RVM in an object. + */ + getRvmInfo(callback?: (rvmInfo: RVMInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the version of the runtime. The version contains the major, minor, build and revision numbers. + */ + getVersion(callback?: (version: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Runs an executable or batch file. + */ + launchExternalProcess(options: ExternalProcessRequestType, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Writes the passed message into both the log file and the console. + */ + log(level: "debug" | "info" | "warn" | "error", message: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Monitors a running process. + */ + monitorExternalProcess(options: ExternalProcessInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Opens the passed URL in the default web browser. + */ + openUrlWithBrowser(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Opens the passed URL in the default web browser. + */ + readRegistryValue(rootKey: string, subkey: string, value: string, callback?: (info: RegistryInfo) => void, + errorCallback?: (reason: string) => void): void; + /** + * This function call will register a unique id and produce a token. The token can be used to broker an external connection. + */ + registerExternalConnection( + uuid: string, + callback?: (detail: { + /** + * this will be unique each time + */ + token: string; + /** + * "remote-connection-uuid" + */ + uuid: string; + }) => void, + errorCallback?: (reason: string) => void): void; + /** + * Removes the process entry for the passed UUID obtained from a prior call of fin.desktop.System.launchExternalProcess(). + */ + releaseExternalProcess(processUuid: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinSystemEventType, + listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, + callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Set the minimum log level above which logs will be written to the OpenFin log + */ + setMinLogLevel(logLevel: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the Chrome Developer Tools for the specified window. + */ + showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds. + */ + terminateExternalProcess( + processUuid: string, + timeout: number, + killTree: boolean, + callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, + errorCallback?: (reason: string) => void): void; + terminateExternalProcess( + processUuid: string, + timeout: number, + callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, + errorCallback?: (reason: string) => void): void; + /** + * Update the OpenFin Runtime Proxy settings. + */ + updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface OpenFinWindowStatic { + /** + * Class: Window + * + * new Window(options, callbackopt, errorCallbackopt) + * + * Creates a new OpenFin Window + * + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, + * maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. + * The new window appears in the same process as the parent window. + * @param options - The options of the window + * @param [callback] - Called if the window creation was successful + * @param [callback.successObj] - httpResponseCode + */ + new ( + options: WindowOption, + callback?: (successObj: { httpResponseCode: number }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow; + /** + * Returns an instance of the current window. + * @returns Current window + */ + getCurrent(): OpenFinWindow; + /** + * Returns a Window object that wraps an existing window. + */ + wrap(appUuid: string, windowName: string): OpenFinWindow; + } + + /** + * Window + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, + * maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. + * The new window appears in the same process as the parent window. + */ + interface OpenFinWindow { + /** + * uuid of the application that the window belongs to. + */ + uuid: string; + /** + * Name of window + */ + name: string; + /** + * Returns the native JavaScript "window" object for the window. This method can only be used by the parent application or the window itself, + * otherwise it will return undefined. The same Single-Origin-Policy (SOP) rules apply for child windows created by window.open(url) in that the + * contents of the window object are only accessible if the URL has the same origin as the invoking window. See example below. + * Also, will not work with fin.desktop.Window objects created with fin.desktop.Window.wrap(). + * @returns Native window + */ + getNativeWindow(): Window; + /** + * Gets the parent application. + * @returns Parent application + */ + getParentApplication(): OpenFinApplication; + /** + * Gets the parent window. + */ + getParentWindow(): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinWindowEventType, + listener: (event: WindowBaseEvent + | WindowAuthRequestedEvent + | WindowBoundsEvent + | WindowExternalProcessStartedEvent + | WindowExternalProcessExited + | WindowGroupChangedEvent + | WindowHiddenEvent + | Window_NavigationRejectedEvent) => void, + callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Performs the specified window transitions + */ + animate(transitions: Transition, options: TransitionOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Provides credentials to authentication requests + */ + authenticate(userName: string, password: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes focus from the window. + */ + blur(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Brings the window to the front of the OpenFin window stack. + */ + bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the window. + * @param Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Prevents a user from changing a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-disabled' is generated when an enabled frame becomes disabled. + */ + disableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Re-enables user changes to a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-enabled' is generated when a disabled frame has becomes enabled. + */ + enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Flashes the window's frame and taskbar icon until the window is activated. + */ + flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gives focus to the window. + */ + focus(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current bounds (top, left, width, height) of the window. + */ + getBounds(callback?: (bounds: Bounds) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned. + * Please note that calling window is included in the result array. + */ + getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current settings of the window. + */ + getOptions(callback?: (options: WindowOption) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets a base64 encoded PNG snapshot of the window. + */ + getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current state ("minimized", "maximized", or "normal") of the window. + */ + getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the zoom level of the window. + */ + getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void; + /** + * Hides the window. + */ + hide(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the window is currently showing. + */ + isShowing(callback?: (showing: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Joins the same window group as the specified window. + */ + joinGroup(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Leaves the current window group so that the window can be move independently of those in the group. + */ + leaveGroup(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Maximizes the window. + */ + maximize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Merges the instance's window group with the same window group as the specified window + */ + mergeGroups(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Minimizes the window. + */ + minimize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window by a specified amount. + */ + moveBy(deltaLeft: number, deltaTop: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window to a specified location. + */ + moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinWindowEventType, + listener: (event: WindowBaseEvent + | WindowAuthRequestedEvent + | WindowBoundsEvent + | WindowExternalProcessStartedEvent + | WindowExternalProcessExited + | WindowGroupChangedEvent + | WindowHiddenEvent + | Window_NavigationRejectedEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeTo(width: number, height: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restores the window to its normal state (i.e., unminimized, unmaximized). + */ + restore(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Will bring the window to the front of the entire stack and give it focus. + */ + setAsForeground(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the window's size and position + */ + setBounds(left: number, top: number, width: number, height: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the zoom level of the window. + */ + setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden. + * @param Show will be prevented from closing when force is false and 'show-requested' has been subscribed to for application's main window. + */ + show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden at the specified location. If the toggle parameter is set to true, the window will alternate between showing and hiding. + */ + showAt(left: number, top: number, force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Stops the taskbar icon from flashing. + */ + stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Updates the window using the passed options + */ + updateOptions(options: WindowOption, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface OpenFinFrameStatic { + wrap(uuid: string, name: string): OpenFinFrame; + + getCurrent(): OpenFinFrame; + } + + interface OpenFinFrame { + name: string; + uuid: string; + + addEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + + getParentWindow(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + + getInfo(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + + removeEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface ApplicationBaseEvent { + topic: string; + type: OpenFinApplicationEventType; + uuid: string; + } + + interface TrayIconClickedEvent extends ApplicationBaseEvent { + button: number; // 0 for left, 1 for middle, 2 for right + monitorInfo: MonitorInfo; + x: number; // the cursor x coordinate + y: number; // the cursor y coordinate + } + + interface WindowEvent extends ApplicationBaseEvent { + name: string; + } + + interface WindowAlertRequestedEvent extends WindowEvent { + message: string; + url: string; + } + + interface WindowAuthRequested extends WindowEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowNavigationRejectedEvent extends WindowEvent { + sourceName: string; + url: string; + } + + interface WindowEndLoadEvent extends WindowEvent { + documentName: string; + isMain: boolean; + } + + interface MonitorInfoChangedEvent extends MonitorInfo { + topic: "system"; + type: "monitor-info-changed"; + } + + interface SystemBaseEvent { + topic: string; + type: OpenFinSystemEventType; + uuid: string; + } + + interface GlobalHotkeyEvent { + topic: string; + type: OpenFinGlobalHotkeyEventType; + /** + * The Identity that has just registered the hotkey + */ + identity: { + name: string; + uuid: string; + parentFrame: string; + entityType: string; + }, + hotkey: string; + } + + interface DesktopIconClickedEvent { + mouse: { + /** + * the left virtual screen coordinate of the mouse + */ + left: number, + /** + * the top virtual screen coordinate of the mouse + */ + top: number + }; + /** + * the number of milliseconds that have elapsed since the system was started, + */ + tickCount: number; + topic: "system"; + type: "desktop-icon-clicked"; + } + + interface IdleStateChangedEvent { + /** + * How long in milliseconds since the user has been idle. + */ + elapsedTime: number; + /** + * true when the user is idle,false when the user has returned; + */ + isIdle: boolean; + topic: "system"; + type: "idle-state-changed"; + } + + interface WindowBaseEvent { + /** + * the name of the window + */ + name: string; + /** + * always window + */ + topic: "window"; + /** + * window event type + */ + type: OpenFinWindowEventType; + /** + * the UUID of the application the window belongs to + */ + uuid: string; + } + + interface WindowAuthRequestedEvent extends WindowBaseEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowBoundsEvent extends WindowBaseEvent { + /** + * describes what kind of change occurred. + * 0 means a change in position. + * 1 means a change in size. + * 2 means a change in position and size. + */ + changeType: number; + /** + * true when pending changes have been applied to the window. + */ + deferred: boolean; + /** + * the new height of the window. + */ + height: number; + /** + * the left-most coordinate of the window. + */ + left: number; + /** + * the top-most coordinate of the window. + */ + top: number; + + type: "bounds-changed" | "bounds-changing" | "disabled-frame-bounds-changed" | "disabled-frame-bounds-changing"; + /** + * the new width of the window. + */ + width: number; + } + + interface WindowExternalProcessStartedEvent extends WindowBaseEvent { + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-started"; + } + + interface WindowExternalProcessExited extends WindowBaseEvent { + /** + * the process exit code + */ + exitCode: number; + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-exited"; + } + + interface WindowGroupChangedEvent extends WindowBaseEvent { + /** + * Which group array the window that the event listener was registered on is included in: + * 'source' The window is included in sourceGroup. + * 'target' The window is included in targetGroup. + * 'nothing' The window is not included in sourceGroup nor targetGroup. + */ + memberOf: "source" | "target" | "nothing"; + /** + * The reason this event was triggered. + * 'leave' A window has left the group due to a leave or merge with group. + * 'join' A window has joined the group. + * 'merge' Two groups have been merged together. + * 'disband' There are no other windows in the group. + */ + reason: "leave" | "join" | "merge" | "disband"; + /** + * All the windows in the group the sourceWindow originated from. + */ + sourceGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the sourceWindow belongs to The source window is the window in which (merge/join/leave)group(s) was called. + */ + sourceWindowAppUuid: string; + /** + * the name of the sourcewindow.The source window is the window in which(merge / join / leave) group(s) was called. + */ + sourceWindowName: string; + /** + * All the windows in the group the targetWindow orginated from + */ + targetGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the targetWindow belongs to. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowAppUuid: string; + /** + * The name of the targetWindow. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowName: string; + type: "group-changed"; + } + + interface WindowOfGroupInfo { + /** + * The UUID of the application this window entry belongs to. + */ + appUuid: string; + /** + * The name of this window entry. + */ + windowName: string; + } + + interface WindowHiddenEvent extends WindowBaseEvent { + /** + * What action prompted the close. + * The reasons are: "hide", "hide-on-close" + */ + reason: "hide" | "hide-on-close"; + type: "hidden"; + } + + interface Window_NavigationRejectedEvent { + name: string; + /** + * source of navigation window name + */ + sourceName: string; + topic: "navigation-rejected"; + /** + * Url that was not reached "http://blocked-content.url" + */ + url: string; + /** + * the UUID of the application the window belongs to. + */ + uuid: string; + } + + interface SessionChangedEvent { + /** + * the action that triggered this event: + */ + reason: "lock" + | "unlock" + | "remote-connect" + | "remote-disconnect" + | "unknown"; + topic: "system"; + type: "session-changed"; + } + + type OpenFinApplicationEventType = "closed" + | "connected" + | "crashed" + | "initialized" + | "manifest-changed" + | "not-responding" + | "out-of-memory" + | "responding" + | "run-requested" + | "started" + | "tray-icon-clicked" + | "window-alert-requested" + | "window-auth-requested" + | "window-closed" + | "window-created" + | "window-end-load" + | "window-navigation-rejected" + | "window-show-requested" + | "window-start-load"; + + type OpenFinExternalApplicationEventType = "connected" + | "disconnected"; + + type OpenFinGlobalHotkeyEventType = "registered" + | "unregistered"; + + type OpenFinSystemEventType = "application-closed" + | "application-crashed" + | "application-created" + | "application-started" + | "desktop-icon-clicked" + | "idle-state-changed" + | "monitor-info-changed" + | "session-changed"; + + type OpenFinWindowEventType = "auth-requested" + | "blurred" + | "bounds-changed" + | "bounds-changing" + | "close-requested" + | "closed" + | "disabled-frame-bounds-changed" + | "disabled-frame-bounds-changing" + | "embedded" + | "external-process-exited" + | "external-process-started" + | "focused" + | "frame-disabled" + | "frame-enabled" + | "group-changed" + | "hidden" + | "initialized" + | "maximized" + | "minimized" + | "navigation-rejected" + | "restored" + | "show-requested" + | "shown"; +} diff --git a/types/openfin/v37/openfin-tests.ts b/types/openfin/v37/openfin-tests.ts new file mode 100644 index 0000000000..5367823dae --- /dev/null +++ b/types/openfin/v37/openfin-tests.ts @@ -0,0 +1,851 @@ +function test_application() { + let application: fin.OpenFinApplication; + // constructor + application = new fin.desktop.Application({ + url: "application.html", + uuid: "74BED629-2D8E-4141-8582-73E364BDFA74", + name: "Application Name", + plugins: false, + mainWindowOptions: { + defaultHeight: 600, + defaultWidth: 800, + defaultTop: 300, + defaultLeft: 300, + autoShow: true + } + }, (successObj) => { + console.log("Application successfully created, HTTP response code:", successObj); + application.run(); + }, (error) => { + console.log("Error creating application:", error); + }); + // createFromManifest + fin.desktop.Application.createFromManifest("http://stuf.com/app.json", (app) => { + console.log(app.uuid); + }, err => console.log(err)); + // getCurrent + application = fin.desktop.Application.getCurrent(); + // wrap + application = fin.desktop.Application.wrap("454C7F31-A915-4EA2-83F2-CFA655453C52"); + // getWindow + application.getWindow(); + // addEventListener + application.addEventListener("closed", (event) => { + console.log("The application has closed"); + }, () => { + console.log("The registration was successful"); + }, reason => { + console.log("failure: " + reason); + }); + // close + application.close(); + // getChildWindows + application.getChildWindows(children => { + children.forEach(childWindow => { + console.log("Showing child: " + childWindow.name); + childWindow.show(); + }); + }); + // getGroups + application.getGroups(allGroups => { + console.log(`There are a total of ${allGroups.length} groups.`); + + let groupCounter = 1; + allGroups.forEach(windowGroup => { + console.log(`Group ${groupCounter} contains ${windowGroup.length} windows.`); + ++groupCounter; + }); + }); + // getManifest + application.getManifest(manifest => { + console.log("Application manifest:"); + console.log(manifest); + }); + // getParentUuid + application.getParentUuid(parentUuid => { + console.log("UUID of parent application:"); + console.log(parentUuid); + }); + // getShortcuts + application.getShortcuts(config => { + console.log("Desktop shortcut is enabled: ", config.desktop); + console.log("Start Menu shortcut is enabled: ", config.startMenu); + console.log("System Startup shortcut is enabled: ", config.systemStartup); + }); + // getInfo + application.getInfo(info => { + console.log(`Launch mode: ${info.launchMode}`); + }); + // getTrayIconInfo + application.getTrayIconInfo(info => { + console.log(info.x, info.y, info.bounds.left, info.bounds.top, info.bounds.height, info.bounds.width, + info.monitorInfo.reason); + }); + // isRunning + application.isRunning(running => { + console.log("the application is", running ? "running" : "not running"); + }); + // registerCustomData + application.registerUser("a", "b", () => console.log("done"), err => console.log(err)); + // removeEventListener + application.removeEventListener("closed", (event: any) => { + console.log(event); + }, () => { + console.log("The unregistration was successful"); + }, err => { + console.log("failure:", err); + }); + // removeTrayIcon + application.removeTrayIcon(() => { + console.log("Removed the tray icon."); + }, err => { + console.log("failure:", err); + }); + // restart + application.restart(() => { + console.log("You will not read this."); + }, err => { + console.log("failure:", err); + }); + // schedule restart + application.scheduleRestart(() => { + console.log("You will not read this."); + }, err => { + console.log("failure:", err); + }); + // setShortcuts + application.setShortcuts({ + desktop: true, + startMenu: false, + systemStartup: true + }, () => { + console.log("Successfully set new shortcut states"); + }, error => { + console.log("Failed to set new shortcut states. Error: ", error); + }); + // setTrayIcon + application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { + console.log(`The mouse has clicked at (${clickInfo.x}, ${clickInfo.y})`); + }); + // terminate + application.terminate(); + // wait + application.addEventListener("not-responding", () => { + console.log("waiting for hung application"); + application.wait(); + }); + // uuid + const hasUuid = application.uuid; +} + +function test_external_application() { + let externalApp: fin.OpenFinExternalApplication; + // wrap + externalApp = fin.desktop.ExternalApp.wrap('my-uuid'); + // addEventListener + externalApp.addEventListener('connected', () => { + console.log('external app connected'); + }, () => { + console.log('The registration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + // removeEventListener + const previousCallback = () => { }; + externalApp.removeEventListener('connected', previousCallback, () => { + console.log('The unregistration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + + // getInfo + externalApp.getInfo(info => { + console.log(info.parent.uuid, info.parent.name); + }, err => console.log(err)); +} + +function test_global_hot_key() { + // addEventListener + fin.desktop.GlobalHotkey.addEventListener('registered', (event) => { + console.log(` window ${event.identity.name} has registered ${event.hotkey}`, event); + }, () => { + console.log('The registration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + // isRegister + const hotkey = 'CommandOrControl+X'; + fin.desktop.GlobalHotkey.isRegistered(hotkey, registered => { + console.log(`hotkey ${hotkey} is registered ? ${registered}`); + }, (reason, err) => { + console.log('Error unregistering the hotkey', err); + }); + // register + fin.desktop.GlobalHotkey.register(hotkey, () => { + console.log(`${hotkey} pressed`); + }, () => { + console.log('Success'); + }, (reason, err) => { + console.log('Error registering the hotkey', err); + }); + // removeEventListener + const previousCallback = () => { }; + fin.desktop.GlobalHotkey.removeEventListener('registered', previousCallback, () => { + console.log('The unregistration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + // unregister + fin.desktop.GlobalHotkey.unregister(hotkey, () => { + console.log('Success'); + }, (reason, err) => { + console.log('Error unregistering the hotkey', err); + }); + // unregisterAll + fin.desktop.GlobalHotkey.unregisterAll(() => { + console.log('Success'); + }, (reason, err) => { + console.log('Error unregistering all hotkeys for this application', err); + }); +} + +function test_inter_application_bus() { + // addSubscribeListener + fin.desktop.InterApplicationBus.addSubscribeListener((uuid, topic, name) => { + console.log(`The application ${uuid} has subscribed to ${topic}`); + }); + // addUnsubscribeListener + fin.desktop.InterApplicationBus.addUnsubscribeListener((uuid, topic, name) => { + console.log(`The application ${uuid} has unsubscribed to ${topic}`); + }); + // removeSubscribeListener + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; + fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); + // removeUnsubscribeListener + fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); + // publish + fin.desktop.InterApplicationBus.publish("a topic", { + field1: "value1", + field2: "value2" + }); + // send + fin.desktop.InterApplicationBus.send("an application's uuid", "a topic", { + field1: "value1", + field2: "value2" + }); + // subscribe + fin.desktop.InterApplicationBus.subscribe("*", "a topic", (message, uuid, name) => { + console.log(`The application ${uuid} sent this message: ${message}`); + }); + // unsubscribe + const aRegisteredMessageListener = (message: any, senderUuid: string) => { + console.log(message, senderUuid); + }; + fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); +} + +function test_notification() { + let notification: fin.OpenFinNotification; + // getCurrent + notification = fin.desktop.Notification.getCurrent(); + // close + notification.close(); + // sendMessage + notification = new fin.desktop.Notification({ + timeout: 10, + url: "http://localhost:5000/Account/Register", + message: "Hello", + onShow: () => { }, + // onClose: () => { }, + onDismiss: () => { }, + // onClick: () => { }, + onMessage: () => { }, + onError: () => { } + }); + // sendMessageToApplication + notification.sendMessageToApplication("some message"); +} + +function test_system() { + // addEventListener + fin.desktop.System.addEventListener('monitor-info-changed', event => { + console.log("The monitor information has changed to: ", event); + }, () => { + console.log("The registration was successful"); + }, err => { + console.log("failure: " + err); + }); + // clearCache + fin.desktop.System.clearCache({ + cache: true, + cookies: true, + localStorage: true, + appcache: true + }); + // deleteCacheOnExit + fin.desktop.System.deleteCacheOnExit(() => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // downloadAsset + const dirAppAsset = { + src: 'http://local:8000/dir.zip', + alias: 'dirApp', + version: '1.23.24', + target: 'dir.bat', + args: '' + }; + fin.desktop.System.downloadAsset(dirAppAsset, progress => { + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + console.log(`Downloaded ${downloadedPercent}%`); + }, p => { + console.log(`Downlod complete, can be found on ${p.path}`); + // lets launch our application asset. + // launchDirApp(); + }, (reason, err) => { + console.log(reason, err); + }); + // downloadRuntime + fin.desktop.System.downloadRuntime({ version: '9.61.31.56' }, progress => { + console.log(progress.downloadedBytes, progress.downloadedBytes); + }, () => console.log('download complete'), err => console.error(err)); + // downloadPreloadScript + const preloadScripts = [ + { url: 'http://whatever.com/script.js' } + ]; + fin.desktop.System.downloadPreloadScripts(preloadScripts, info => { + const downloadInfo = info[0]; + console.log(downloadInfo.success, downloadInfo.url, downloadInfo.error); + }, err => { + console.log(err); + }); + // exit + fin.desktop.System.exit(() => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // flushCookieStore + fin.desktop.System.flushCookieStore(() => { + console.log('successful'); + }, err => { + console.log('failure', err); + }); + // getAllApplications + fin.desktop.System.getAllApplications(applicationInfoList => { + applicationInfoList.forEach(applicationInfo => { + console.log("Showing information for application with uuid: " + + applicationInfo.uuid); + console.log("isRunning: ", applicationInfo.isRunning); + }); + }); + // getAllExternalApplications + fin.desktop.System.getAllExternalApplications(externalAppsInfoList => { + externalAppsInfoList.forEach(appInfo => { + console.log(`External app connected to the runtime with UUID ${appInfo.uuid}`); + }); + }); + // getAllWindows + fin.desktop.System.getAllWindows(windowInfoList => { + windowInfoList.forEach(windowInfo => { + console.log("Showing information for application with uuid: ", windowInfo.uuid); + console.log("Main window: ", windowInfo.mainWindow); + console.log("Child windows: ", windowInfo.childWindows); + }); + }); + // getAppAssetInfo + fin.desktop.System.getAppAssetInfo({ alias: 'myAppAsset' }, info => { + console.log(info.alias, info.args, info.mandatory, info.src, info.target, info.version); + }, err => console.log(err)); + // getCommandLineArguments + fin.desktop.System.getCommandLineArguments(args => { + console.log("The command line arguments are " + args); + }); + // getCookieInfo + fin.desktop.System.getCookies({ name: 'myCookie1'}, cookies => { + const cookie1 = cookies[0]; + console.log(cookie1.name, cookie1.domain, cookie1.path); + }, err => console.log(err)); + // getDeviceId + fin.desktop.System.getDeviceId(id => { + console.log("The id of the device is: " + id); + }); + // getDeviceUserId + fin.desktop.System.getDeviceUserId(id => console.log(id), err => console.error(err)); + // getEntityInfo + fin.desktop.System.getEntityInfo('uuid', 'name', info => { + console.log(info.entityType, info.name, info.uuid, info.parent.name, info.parent.uuid); + }, err => console.log(err)); + // getEnvironmentVariable + fin.desktop.System.getEnvironmentVariable("APPDATA", variable => { + console.log("this is the APPDATA value", variable); + }); + // getFocusedWindow + fin.desktop.System.getFocusedWindow(win => { + console.log(win.uuid, win.name); + }, err => console.log(err)); + // getHostSpecs + fin.desktop.System.getHostSpecs(info => { + console.log(info); + }, error => { + console.log('There was an error:', error); + }); + // getLog + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', log => { + console.log(log); + }); + // getLogList + fin.desktop.System.getLogList(logList => { + logList.forEach(logInfo => { + console.log(`The filename of the log is ${logInfo.name}, the size is ${logInfo.size}, and the date of creation is ${logInfo.date}`); + }); + }); + // getMinLogLevel + fin.desktop.System.getMinLogLevel(level => console.log(level), err => console.log(err)); + // getMonitorInfo + fin.desktop.System.getMonitorInfo(monitorInfo => { + console.log("This object contains information about all monitors: ", monitorInfo); + }); + // getMousePosition + fin.desktop.System.getMousePosition(mousePosition => { + console.log(`The mouse is located at left: ${mousePosition.left}, top: ${mousePosition.top}`); + }); + // getProcessList + fin.desktop.System.getProcessList(list => { + list.forEach(process => { + console.log(`UUID: ${process.uuid}, Application Name: ${process.name}`); + }); + }); + // getProxySettings + fin.desktop.System.getProxySettings(proxy => { + console.log(proxy); + }); + // getRuntimeInfo + fin.desktop.System.getRuntimeInfo(runtimeInfoObject => { + console.log("Runtime version:", runtimeInfoObject.version); + console.log("Runtime architecture:", runtimeInfoObject["architecture"]); + }, err => { + console.log("Failed to get runtime info, error message:", err); + }); + // getRvmInfo + fin.desktop.System.getRvmInfo(rvmInfoObject => { + console.log("RVM version:", rvmInfoObject.version); + console.log("RVM has been running since:", rvmInfoObject["start-time"]); + }, err => { + console.log("Failed to get rvm info, error message:", err); + }); + // getVersion + fin.desktop.System.getVersion(version => { + console.log("The version is " + version); + }); + // launchExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // launch external process with an alias + fin.desktop.System.launchExternalProcess({ + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default + alias: "myApp", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + alias: "myApp", + arguments: "e f g", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + path: "C:\Users\ExampleUser\AppData\Local\OpenFin\OpenFinRVM.exe", + arguments: "--version", + certificate: { + trusted: true, + subject: 'O=OpenFin INC., L=New York, S=NY, C=US', + thumbprint: '3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' + }, + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // log + fin.desktop.System.log("info", "An example log message", () => { + console.log("message successfully logged"); + }, err => { + console.log(err); + }); + // monitorExternalProcess + fin.desktop.System.monitorExternalProcess({ + pid: 2508, + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log("The process is now being monitored: ", payload.uuid); + }, error => { + console.log("Error:", error); + }); + // openUrlWithBrowser + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", () => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // readRegistryValue + fin.desktop.System.readRegistryValue('HKEY_SOMETHING', 'HARDWARE\\SOMETHING', 'BootSomething', info => { + console.log(info.data, info.rootKey, info.subkey, info.type, info.value); + }, err => console.log(err)); + // registerExternalConnection + fin.desktop.System.registerExternalConnection("remote-connection-uuid", (...args: any[]) => { + console.log(args); + }); + // releaseExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener(result) { + console.log("The exit code", result.exitCode); + } + }, result => { + console.log("Result UUID is " + result.uuid); + + // release it. + fin.desktop.System.releaseExternalProcess(result.uuid, () => { + console.log("Process has been unmapped!"); + }, reason => { + console.log("failure: " + reason); + }); + }); + // removeEventListener + fin.desktop.System.removeEventListener("monitor-info-changed", (event) => { + console.log(event); + }, () => { + console.log("successful"); + }, (err: any) => { + console.log("failure: " + err); + }); + // setMinLogLevel + fin.desktop.System.setMinLogLevel("log level", () => console.log('Success'), (err: any) => console.error(err)); + // showDeveloperTools + fin.desktop.System.showDeveloperTools("uuid", "name", () => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // terminateExternalProcess + fin.desktop.System.launchExternalProcess({ + // notepad is in the system's PATH + path: "notepad", + arguments: "", + listener(result) { + console.log("The exit code", result.exitCode); + } + }, result => { + console.log("Result UUID is " + result.uuid); + + // Attempt to close the process. Terminate after 4 seconds if it + // has not done so. + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { + console.log("Termination result " + info.result); + }, reason => { + console.log("failure: " + reason); + }); + }); + // updateProxySettings + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, () => { + console.log('success'); + }, err => { + console.log(err); + }); +} + +function test_system_clipboard() { + // availableFormats + fin.desktop.System.Clipboard.availableFormats(null, formats => { + formats.forEach(format => console.log(`The format ${format} is available to read`)); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readHtml + fin.desktop.System.Clipboard.readHtml(null, html => { + console.log(`This is the html from the clipboard: ${html}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readRtf + fin.desktop.System.Clipboard.readRtf(null, rtf => { + console.log(`This is the rtf from the clipboard: ${rtf}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readText + fin.desktop.System.Clipboard.readText(null, text => { + console.log(`This is the text from the clipboard: ${text}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // write + fin.desktop.System.Clipboard.write({ + text: 'Hello Text!', + html: '

    Hello Html

    ', + rtf: 'Hello Rtf' + }, null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeHtml + fin.desktop.System.Clipboard.writeHtml('

    Hello World

    ', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeRtf + fin.desktop.System.Clipboard.writeRtf('Hello World!', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeText + fin.desktop.System.Clipboard.writeText('Hello World', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); +} + +function test_window() { + let finWindow: fin.OpenFinWindow; + // constructor + finWindow = new fin.desktop.Window({ + name: "childWindow", + url: "child.html", + defaultWidth: 320, + defaultHeight: 320, + defaultTop: 10, + defaultLeft: 300, + frame: false, + resizable: false, + state: "normal" + }, () => { + const _win = finWindow.getNativeWindow(); + _win.addEventListener("DOMContentLoaded", () => { finWindow.show(); }); + }, error => { + console.log("Error creating window:", error); + }); + // getCurrent + finWindow = fin.desktop.Window.getCurrent(); + // getNativeWindow + let nativeWindow: Window; + nativeWindow = finWindow.getNativeWindow(); + // getParentApplication + let parentApp: fin.OpenFinApplication; + parentApp = finWindow.getParentApplication(); + // getParentWindow + let parentFinWindow: fin.OpenFinWindow; + parentFinWindow = finWindow.getParentWindow(); + // wrap + finWindow = fin.desktop.Window.wrap("uuid", "name"); + // addEventListener + finWindow.addEventListener("bounds-changed", event => { + console.log("The window has been moved or resized"); + }, () => { + console.log("The registration was successful"); + }, reason => { + console.log("failure:" + reason); + }); + // animate + finWindow.animate({ + opacity: { + opacity: 0.15, + duration: 1000 + }, + position: { + left: 10, + top: 10, + duration: 3000 + } + }, { + interrupt: false + }, evt => { + // Callback will only fire after both "opacity" and "position" have finished animating. + }); + // authenticate + finWindow.addEventListener('auth-requested', evt => { + finWindow.authenticate('userName', 'P@assw0rd', () => { }, (reason, err) => { + console.log("failure:", err); + }); + }); + // blur + finWindow.blur(); + // bringToFront + finWindow.bringToFront(); + // close + finWindow.close(); + // disableFrame + finWindow.disableFrame(); + // enableFrame + finWindow.enableFrame(); + // flash + finWindow.flash(); + // focus + finWindow.focus(); + // getBounds + finWindow.getBounds(bounds => { + console.log(`top: ${bounds.top} left: ${bounds.left} height: ${bounds.height} width: ${bounds.width}`); + }); + // getOptions + finWindow.getOptions(options => { + console.log(options); + }); + // getSnapshot + finWindow.getSnapshot(base64Snapshot => { + console.log("data:image/png;base64," + base64Snapshot); + }); + // getState + finWindow.getState(state => { + console.log("state: " + state); + }); + // getZoomLevel + finWindow.getZoomLevel(level => { + console.log("zoom level: " + level); + }, error => { + console.log('error:', error); + }); + // hide + finWindow.hide(); + // isShowing + finWindow.isShowing(showing => { + console.log("the window is " + (showing ? "showing" : "hidden")); + }); + // joinGroup + let secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, () => { + // When mainWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow); + }); + // leaveGroup + secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, () => { + // When finWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow, () => { + // once we are in the group, lets leave it. + secondWindow.leaveGroup(); + }); + }); + // maximize + finWindow.maximize(); + // mergeGroups + { + const finWindowOne = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowOne", + autoShow: true + }); + const finWindowTwo = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowTwo", + autoShow: true + }); + const finWindowThree = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowThree", + autoShow: true + }); + const finWindowFour = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowFour", + autoShow: true + }); + // When finWindowOne moves or is moved, finWindowTwo moves by the same amount + finWindowOne.joinGroup(finWindowTwo); + // When finWindowThree moves or is moved, finWindowFour moves by the same amount + finWindowThree.joinGroup(finWindowFour); + // finWindowOne, finWindowTwo, finWindowThree, and finWindowFour now move together in the same group + finWindowOne.mergeGroups(finWindowThree); + } + // minimize + finWindow.minimize(); + // moveBy + finWindow.moveBy(10, 10); + // moveTo + finWindow.moveTo(100, 200); + // removeEventListener + finWindow.removeEventListener("bounds-changed", event => { + console.log(event); + }); + // resizeBy + finWindow.resizeBy(10, 10, "top-right"); + // resizeTo + finWindow.resizeTo(10, 10, "top-right"); + // restore + finWindow.restore(); + // setAsForeground + finWindow.setAsForeground(); + // setBounds + finWindow.setBounds(100, 200, 400, 400); + // setZoomLevel + finWindow.setZoomLevel(10); + // show + finWindow.show(); + // showAt + finWindow.showAt(10, 10, false); + // stopFlashing + finWindow.stopFlashing(); + // updateOptions + finWindow.updateOptions({ + frame: false, + maxWidth: 500 + }); +} + +function test_frame() { + // wrap + const frame = fin.desktop.Frame.wrap('uuid', 'name'); + // getCurrent + const currentFrame = fin.desktop.Frame.getCurrent(); + // addEventlistener + frame.addEventListener('event', () => console.log('on event'), () => console.log('success'), err => console.error(err)); + // removeEventListener + frame.removeEventListener('event', () => console.log('on event'), () => console.log('success'), err => console.error(err)); + // getInfo + frame.getInfo(info => { + console.log(info.uuid, info.name, info.entityType, info.parent.uuid, info.parent.name); + }, err => console.error(err)); + // getParentWindow + frame.getParentWindow(parent => { + console.log(parent.uuid, parent.name, parent.entityType, parent.parent.uuid, parent.parent.name); + }, err => console.error(err)); +} diff --git a/types/openfin/v37/tsconfig.json b/types/openfin/v37/tsconfig.json new file mode 100644 index 0000000000..1847c9c9d2 --- /dev/null +++ b/types/openfin/v37/tsconfig.json @@ -0,0 +1,84 @@ +{ + "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", + "openfin-tests.ts", + "_v2/api/application/application.d.ts", + "_v2/api/application/applicationOption.d.ts", + "_v2/api/base.d.ts", + "_v2/api/clipboard/clipboard.d.ts", + "_v2/api/clipboard/write-request.d.ts", + "_v2/api/external-application/external-application.d.ts", + "_v2/api/fin.d.ts", + "_v2/api/frame/frame.d.ts", + "_v2/api/global-hotkey/index.d.ts", + "_v2/api/interappbus/channel/channel.d.ts", + "_v2/api/interappbus/channel/client.d.ts", + "_v2/api/interappbus/channel/index.d.ts", + "_v2/api/interappbus/channel/provider.d.ts", + "_v2/api/interappbus/interappbus.d.ts", + "_v2/api/notification/notification.d.ts", + "_v2/api/system/application.d.ts", + "_v2/api/system/clearCacheOption.d.ts", + "_v2/api/system/cookie.d.ts", + "_v2/api/system/crashReporterOption.d.ts", + "_v2/api/system/download-asset.d.ts", + "_v2/api/system/download-preload.d.ts", + "_v2/api/system/entity.d.ts", + "_v2/api/system/external-process.d.ts", + "_v2/api/system/host-specs.d.ts", + "_v2/api/system/log.d.ts", + "_v2/api/system/monitor.d.ts", + "_v2/api/system/point.d.ts", + "_v2/api/system/process.d.ts", + "_v2/api/system/proxy.d.ts", + "_v2/api/system/registry-info.d.ts", + "_v2/api/system/runtime-info.d.ts", + "_v2/api/system/rvm.d.ts", + "_v2/api/system/system.d.ts", + "_v2/api/system/window.d.ts", + "_v2/api/window/anchor-type.d.ts", + "_v2/api/window/bounds-changed.d.ts", + "_v2/api/window/bounds.d.ts", + "_v2/api/window/transition.d.ts", + "_v2/api/window/window.d.ts", + "_v2/api/window/windowOption.d.ts", + "_v2/environment/environment.d.ts", + "_v2/environment/node-env.d.ts", + "_v2/environment/openfin-env.d.ts", + "_v2/environment/openfin-renderer-api.d.ts", + "_v2/identity.d.ts", + "_v2/launcher/launcher.d.ts", + "_v2/launcher/nix-launch.d.ts", + "_v2/launcher/util.d.ts", + "_v2/launcher/win-launch.d.ts", + "_v2/main.d.ts", + "_v2/of-main.d.ts", + "_v2/transport/elipc.d.ts", + "_v2/transport/port-discovery.d.ts", + "_v2/transport/transport-errors.d.ts", + "_v2/transport/transport.d.ts", + "_v2/transport/websocket.d.ts", + "_v2/transport/wire.d.ts", + "_v2/util/normalize-config.d.ts", + "_v2/util/promises.d.ts", + "_v2/util/ref-counter.d.ts" + ] +} diff --git a/types/openfin/v37/tslint.json b/types/openfin/v37/tslint.json new file mode 100644 index 0000000000..f95a4974aa --- /dev/null +++ b/types/openfin/v37/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": false, + "no-redundant-jsdoc-2": false, + "jsdoc-format": false, + "no-var-keyword": false, + "whitespace": false, + "semicolon": false, + "strict-export-declare-modifiers": false, + "array-type": false, + "unified-signatures": false, + "void-return": false, + "ban-types": false, + "callable-types": false, + "no-const-enum": false + } +} From cc2043909f0e015830241affc9f847982ef6dc8e Mon Sep 17 00:00:00 2001 From: Daniel Rose Date: Tue, 29 Jan 2019 19:51:16 +0100 Subject: [PATCH 173/312] Add missing methods of SCServerSocket. (#32589) Also updates and fixes some properties missing in SCServer. --- types/socketcluster-server/scserver.d.ts | 8 ++- .../socketcluster-server/scserversocket.d.ts | 54 ++++++++++++++++++- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts index c04c4888f0..d6e808b245 100644 --- a/types/socketcluster-server/scserver.d.ts +++ b/types/socketcluster-server/scserver.d.ts @@ -3,7 +3,7 @@ import { Secret } from "jsonwebtoken"; import { ServerOptions } from "https"; import { IncomingMessage, Server } from "http"; import { SCAuthEngine } from "sc-auth"; -import { SCExchange } from "sc-broker-cluster"; +import { SCExchange, Client } from "sc-broker-cluster"; import WebSocket = require("ws"); import SCServerSocket = require("./scserversocket"); @@ -18,6 +18,7 @@ declare class SCServer extends EventEmitter { readonly MIDDLEWARE_EMIT: "emit"; options: SCServer.SCServerOptions; + brokerEngine: Client; exchange: SCExchange; clients: { @@ -58,7 +59,10 @@ declare class SCServer extends EventEmitter { removeMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; setAuthEngine(authEngine: SCAuthEngine): void; + auth: SCAuthEngine; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + codec: SCServer.SCCodecEngine; close(cb?: (err?: Error) => void): void; @@ -348,7 +352,7 @@ declare namespace SCServer { interface SCCodecEngine { decode: (input: any) => any; - ncode: (object: any) => any; + encode: (object: any) => any; } interface VerifyHandshakeInfo { diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts index 7b32cef72c..c4440a13f3 100644 --- a/types/socketcluster-server/scserversocket.d.ts +++ b/types/socketcluster-server/scserversocket.d.ts @@ -29,15 +29,65 @@ declare class SCServerSocket extends Emitter { constructor(id: string, server: SCServer, socket: WebSocket); + on(event: "error", listener: (error: Error) => void): this; + on(event: "message" | "raw", listener: (message: WebSocket.Data) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data?: any) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCServerSocket.StateChangeData) => void): this; + on(event: "authenticate", listener: (authToken?: SCServer.AuthToken) => void): this; + on(event: "deauthenticate", listener: (oldToken?: SCServer.AuthToken) => void): this; + getState(): "connecting" | "open" | "closed"; + getBytesReceived(): number; + disconnect(code?: number, data?: any): void; + destroy(code?: number, data?: any): void; + terminate(): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + + decode(message: any): any; + encode(object: any): any; + + sendObjectBatch(object: any): void; + sendObjectSingle(object: any): void; + sendObject(object: any, options?: { batch?: boolean }): void; + + emit(event: string, ...args: any[]): boolean; + emit(event: string, data: any, callback?: SCServerSocket.EmitCallback, options?: SCServerSocket.EmitOptions): void; + + triggerAuthenticationEvents(oldState: "authenticated" | "unauthenticated"): void; + getAuthToken(): SCServer.AuthToken; - setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; - deauthenticate(): void; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions, callback?: SCServerSocket.EmitCallback): void; + + deauthenticateSelf(): void; + deauthenticate(callback?: SCServerSocket.EmitCallback): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; isSubscribed(channel?: string): boolean; } export = SCServerSocket; + +declare namespace SCServerSocket { + type EmitCallback = (err: Error, eventObject: EventObject) => void; + + interface EventObject { + event: string; + data?: any; + cid?: number; + } + + interface EmitOptions { + useCache?: boolean; + stringifiedData?: string; + } + + interface StateChangeData { + oldState: "authenticated" | "unauthenticated"; + newState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + } +} From 22ba29d7a075d4054d135ce3eee33a27807c4dda Mon Sep 17 00:00:00 2001 From: Tobi Date: Tue, 29 Jan 2019 20:00:40 +0100 Subject: [PATCH 174/312] [koa-bouncer] fixes ValidatorError/ValidationError typo (#32481) --- types/koa-bouncer/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/koa-bouncer/index.d.ts b/types/koa-bouncer/index.d.ts index 7b881f2b5c..af3a8b6693 100644 --- a/types/koa-bouncer/index.d.ts +++ b/types/koa-bouncer/index.d.ts @@ -7,7 +7,7 @@ import { Middleware, Context } from 'koa'; declare namespace KoaBouncer { - export class ValidatorError extends Error { + export class ValidationError extends Error { name: string; message: string; bouncer: { @@ -88,4 +88,4 @@ declare module "koa" { } } -export = KoaBouncer; \ No newline at end of file +export = KoaBouncer; From 3f82b25685b06bc42264d0f0a0c75174372ea3db Mon Sep 17 00:00:00 2001 From: licui Date: Tue, 29 Jan 2019 14:10:25 -0500 Subject: [PATCH 175/312] Update to v39 --- .../_v2/api/application/application.d.ts | 196 +++++- types/openfin/_v2/api/base.d.ts | 15 +- .../openfin/_v2/api/clipboard/clipboard.d.ts | 2 +- types/openfin/_v2/api/events/window.d.ts | 16 +- .../external-application.d.ts | 80 ++- types/openfin/_v2/api/frame/frame.d.ts | 80 ++- .../_v2/api/interappbus/channel/channel.d.ts | 4 +- .../interappbus/channel/channels-docs.d.ts | 266 ++++++++ .../_v2/api/interappbus/channel/client.d.ts | 5 + .../_v2/api/interappbus/channel/index.d.ts | 1 + .../_v2/api/interappbus/channel/provider.d.ts | 4 +- .../_v2/api/interappbus/interappbus.d.ts | 2 +- .../_v2/api/notification/notification.d.ts | 11 + types/openfin/_v2/api/system/monitor.d.ts | 2 +- types/openfin/_v2/api/system/system.d.ts | 244 ++++++- types/openfin/_v2/api/window/window.d.ts | 639 +++++++++--------- types/openfin/index.d.ts | 4 +- 17 files changed, 1155 insertions(+), 416 deletions(-) create mode 100644 types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts diff --git a/types/openfin/_v2/api/application/application.d.ts b/types/openfin/_v2/api/application/application.d.ts index 37263a9a63..677e1cd992 100644 --- a/types/openfin/_v2/api/application/application.d.ts +++ b/types/openfin/_v2/api/application/application.d.ts @@ -19,6 +19,9 @@ export interface ApplicationInfo { parentUuid?: string; runtime: object; } +export interface LogInfo { + logId: string; +} export declare class NavigationRejectedReply extends Reply<'window-navigation-rejected', void> { sourceName: string; url: string; @@ -34,6 +37,64 @@ export interface TrayInfo { x: number; y: number; } +/** + * @typedef {object} Application~options + * @summary Application creation options. + * @desc This is the options object required by {@link Application.create Application.create}. + * + * The following options are required: + * * `uuid` is required in the app manifest as well as by {@link Application.create Application.create} + * * `name` is optional in the app manifest but required by {@link Application.create Application.create} + * * `url` is optional in both the app manifest {@link Application.create Application.create} and but is usually given + * (defaults to `"about:blank"` when omitted). + * + * _This jsdoc typedef mirrors the `ApplicationOptions` TypeScript interface in `@types/openfin`._ + * + * **IMPORTANT NOTE:** + * This object inherits all the properties of the window creation {@link Window~options options} object, + * which will take priority over those of the same name that may be provided in `mainWindowOptions`. + * + * @property {boolean} [disableIabSecureLogging=false] + * When set to `true` it will disable IAB secure logging for the app. + * + * @property {string} [loadErrorMessage="There was an error loading the application."] + * An error message to display when the application (launched via manifest) fails to load. + * A dialog box will be launched with the error message just before the runtime exits. + * Load fails such as failed DNS resolutions or aborted connections as well as cancellations, _e.g.,_ `window.stop()`, + * will trigger this dialog. + * Client response codes such as `404 Not Found` are not treated as fails as they are valid server responses. + * + * @property {Window~options} [mainWindowOptions] + * The options of the main window of the application. + * For a description of these options, click the link (in the Type column). + * + * @property {string} [name] + * The name of the application (and the application's main window). + * + * If provided, _must_ match `uuid`. + * + * @property {boolean} [nonPersistent=false] + * A flag to configure the application as non-persistent. + * Runtime exits when there are no persistent apps running. + * + * @property {boolean} [plugins=false] + * Enable Flash at the application level. + * + * @property {boolean} [spellCheck=false] + * Enable spell check at the application level. + * + * @property {string} [url="about:blank"] + * The url to the application (specifically the application's main window). + * + * @property {string} uuid + * The _Unique Universal Identifier_ (UUID) of the application, unique within the set of all other applications + * running in the OpenFin Runtime. + * + * Note that `name` and `uuid` must match. + * + * @property {boolean} [webSecurity=true] + * When set to `false` it will disable the same-origin policy for the app. + */ /** * @lends Application */ @@ -54,14 +115,16 @@ export default class ApplicationModule extends Base { * @static */ wrapSync(identity: Identity): Application; - /** - * Creates a new Application. - * @param { ApplicationOption } appOptions - * @return {Promise.} - * @tutorial Application.create - * @static - */ + private _create; create(appOptions: ApplicationOption): Promise; + /** + * Creates and starts a new Application. + * @param { ApplicationOption } appOptions + * @return {Promise.} + * @tutorial Application.start + * @static + */ + start(appOptions: ApplicationOption): Promise; /** * Asynchronously returns an Application object that represents the current application * @return {Promise.} @@ -77,18 +140,20 @@ export default class ApplicationModule extends Base { */ getCurrentSync(): Application; /** - * Retrieves application's manifest and returns a wrapped application. + * Retrieves application's manifest and returns a running instance of the application. * @param {string} manifestUrl - The URL of app's manifest. * @return {Promise.} - * @tutorial Application.createFromManifest + * @tutorial Application.startFromManifest * @static */ + startFromManifest(manifestUrl: string): Promise; createFromManifest(manifestUrl: string): Promise; } /** * @classdesc An object representing an application. Allows the developer to create, - * execute, show/close an application as well as listen to application events. + * execute, show/close an application as well as listen to application events. * @class + * @hideconstructor */ export declare class Application extends EmitterBase { identity: Identity; @@ -96,6 +161,83 @@ export declare class Application extends EmitterBase { private window; constructor(wire: Transport, identity: Identity); private windowListFromIdentityList; + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function addListener + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function on + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function once + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependListener + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * The listener is added to the beginning of the listeners array. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependOnceListener + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Remove a listener from the listener array for the specified event. + * Caution: Calling this method changes the array indices in the listener array behind the listener. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function removeListener + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ + /** + * Removes all listeners, or those of the specified event. + * @param { string | symbol } [eventType] - The type of the event. + * @return {Promise.} + * @function removeAllListeners + * @memberof Application + * @instance + * @tutorial Application.EventEmitter + */ /** * Determines if the application is currently running. * @return {Promise.} @@ -104,11 +246,14 @@ export declare class Application extends EmitterBase { isRunning(): Promise; /** * Closes the application and any child windows created by the application. + * Cleans the application from state so it is no longer found in getAllApplications. * @param { boolean } [force = false] Close will be prevented from closing when force is false and * ‘close-requested’ has been subscribed to for application’s main window. * @return {Promise.} - * @tutorial Application.close + * @tutorial Application.quit */ + quit(force?: boolean): Promise; + private _close; close(force?: boolean): Promise; /** * Retrieves an array of wrapped fin.Windows for each of the application’s child windows. @@ -175,11 +320,6 @@ export declare class Application extends EmitterBase { * @tutorial Application.restart */ restart(): Promise; - /** - * Runs the application. When the application is created, run must be called. - * @return {Promise.} - * @tutorial Application.run - */ run(): Promise; /** * Instructs the RVM to schedule one restart of the application. @@ -188,7 +328,14 @@ export declare class Application extends EmitterBase { */ scheduleRestart(): Promise; /** - * Adds a customizable icon in the system tray and notifies the application when clicked. + * Sends a message to the RVM to upload the application's logs. On success, + * an object containing logId is returned. + * @return {Promise.} + * @tutorial Application.sendApplicationLog + */ + sendApplicationLog(): Promise; + /** + * Adds a customizable icon in the system tray. To listen for a click on the icon use the `tray-icon-clicked` event. * @param { string } iconUrl Image URL to be used as the icon * @return {Promise.} * @tutorial Application.setTrayIcon @@ -196,10 +343,10 @@ export declare class Application extends EmitterBase { setTrayIcon(iconUrl: string): Promise; /** * Sets new application's shortcut configuration. - * @param { Object } config New application's shortcut configuration. - * @param {Boolean} [config.desktop] - Enable/disable desktop shortcut. - * @param {Boolean} [config.startMenu] - Enable/disable start menu shortcut. - * @param {Boolean} [config.systemStartup] - Enable/disable system startup shortcut. + * @param { ShortCutConfig } config New application's shortcut configuration. + * @param { boolean } [config.desktop] - Enable/disable desktop shortcut. + * @param { boolean } [config.startMenu] - Enable/disable start menu shortcut. + * @param { boolean } [config.systemStartup] - Enable/disable system startup shortcut. * @return {Promise.} * @tutorial Application.setShortcuts */ @@ -212,6 +359,13 @@ export declare class Application extends EmitterBase { * @tutorial Application.setZoomLevel */ setZoomLevel(level: number): Promise; + /** + * Sets a username to correlate with App Log Management. + * @param { string } username Username to correlate with App's Log. + * @return {Promise.} + * @tutorial Application.setAppLogUsername + */ + setAppLogUsername(username: string): Promise; /** * @summary Retrieves information about the system tray. * @desc The only information currently returned is the position and dimensions. diff --git a/types/openfin/_v2/api/base.d.ts b/types/openfin/_v2/api/base.d.ts index 5cbb8658a7..4be094441a 100644 --- a/types/openfin/_v2/api/base.d.ts +++ b/types/openfin/_v2/api/base.d.ts @@ -4,7 +4,7 @@ import { Identity } from '../identity'; import { EventEmitter } from 'events'; import { EmitterAccessor } from './events/emitterMap'; import { BaseEventMap } from './events/base'; -interface SubOptions { +export interface SubOptions { timestamp?: number; } export declare class Base { @@ -28,14 +28,14 @@ export declare class EmitterBase extends Base { listenerCount: (type: string | symbol) => number; protected registerEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; protected deregisterEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; - on | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + on: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; addListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; - once | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; - prependListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; - prependOnceListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; - removeListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + once: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; + prependListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; + prependOnceListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; + removeListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; protected deregisterAllListeners: (eventType: string | symbol | Extract) => Promise; - removeAllListeners(eventType?: Extract | string | symbol): Promise; + removeAllListeners: (eventType?: string | symbol | Extract) => Promise; } export declare class Reply implements Identity { topic: TOPIC; @@ -43,4 +43,3 @@ export declare class Reply imp uuid: string; name?: string; } -export {}; diff --git a/types/openfin/_v2/api/clipboard/clipboard.d.ts b/types/openfin/_v2/api/clipboard/clipboard.d.ts index 11b466dea0..5657984840 100644 --- a/types/openfin/_v2/api/clipboard/clipboard.d.ts +++ b/types/openfin/_v2/api/clipboard/clipboard.d.ts @@ -2,7 +2,7 @@ import { Base } from '../base'; import { WriteRequestType, WriteAnyRequestType } from './write-request'; /** * WriteRequestType interface - * @typedef { Object } WriteRequestType + * @typedef { object } WriteRequestType * @property { string } name The name of the running application * @property { string } uuid The uuid of the running application */ diff --git a/types/openfin/_v2/api/events/window.d.ts b/types/openfin/_v2/api/events/window.d.ts index 85d4d553f0..8899ae0c5a 100644 --- a/types/openfin/_v2/api/events/window.d.ts +++ b/types/openfin/_v2/api/events/window.d.ts @@ -113,15 +113,13 @@ export interface WindowEventMapping extends BaseE 'closed': WindowEvent; 'closing': WindowEvent; 'crashed': CrashedEvent & WindowEvent; - 'disabled-frame-bounds-changed': WindowBoundsChange; - 'disabled-frame-bounds-changing': WindowBoundsChange; + 'disabled-movement-bounds-changed': WindowBoundsChange; + 'disabled-movement-bounds-changing': WindowBoundsChange; 'embedded': WindowEvent; 'end-user-bounds-changing': WindowBeginBoundsChangingEvent; 'external-process-exited': WindowExternalProcessExitedEvent; 'external-process-started': WindowExternalProcessStartedEvent; 'focused': WindowEvent; - 'frame-disabled': WindowEvent; - 'frame-enabled': WindowEvent; 'group-changed': WindowGroupChanged; 'hidden': WindowHiddenEvent; 'initialized': WindowEvent; @@ -136,6 +134,8 @@ export interface WindowEventMapping extends BaseE 'restored': WindowEvent; 'show-requested': WindowEvent; 'shown': WindowEvent; + 'user-movement-disabled': WindowEvent; + 'user-movement-enabled': WindowEvent; } export interface PropagatedWindowEventMapping extends BaseEventMap { 'window-begin-user-bounds-changing': WindowBeginBoundsChangingEvent; @@ -145,15 +145,13 @@ export interface PropagatedWindowEventMapping ext 'window-closed': WindowEvent; 'window-closing': WindowEvent; 'window-crashed': CrashedEvent & WindowEvent; - 'window-disabled-frame-bounds-changed': WindowBoundsChange; - 'window-disabled-frame-bounds-changing': WindowBoundsChange; + 'window-disabled-movement-bounds-changed': WindowBoundsChange; + 'window-disabled-movement-bounds-changing': WindowBoundsChange; 'window-embedded': WindowEvent; 'window-end-user-bounds-changing': WindowBeginBoundsChangingEvent; 'window-external-process-exited': WindowExternalProcessExitedEvent; 'window-external-process-started': WindowExternalProcessStartedEvent; 'window-focused': WindowEvent; - 'window-frame-disabled': WindowEvent; - 'window-frame-enabled': WindowEvent; 'window-group-changed': WindowGroupChanged; 'window-hidden': WindowHiddenEvent; 'window-initialized': WindowEvent; @@ -167,6 +165,8 @@ export interface PropagatedWindowEventMapping ext 'window-reloaded': WindowReloadedEvent; 'window-restored': WindowEvent; 'window-shown': WindowEvent; + 'window-user-movement-disabled': WindowEvent; + 'window-user-movement-enabled': WindowEvent; } export declare type WindowEvents = { [Type in keyof WindowEventMapping]: WindowEventMapping<'window', Type>[Type]; diff --git a/types/openfin/_v2/api/external-application/external-application.d.ts b/types/openfin/_v2/api/external-application/external-application.d.ts index a4f44851e9..1c6bc38dbf 100644 --- a/types/openfin/_v2/api/external-application/external-application.d.ts +++ b/types/openfin/_v2/api/external-application/external-application.d.ts @@ -29,12 +29,90 @@ export default class ExternalApplicationModule extends Base { /** * @classdesc An ExternalApplication object representing an application. Allows * the developer to create, execute, show and close an external application as - * well as listen to application events. + * well as listen to application events. * @class + * @hideconstructor */ export declare class ExternalApplication extends EmitterBase { identity: Identity; constructor(wire: Transport, identity: Identity); + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function addListener + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function on + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function once + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependListener + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * The listener is added to the beginning of the listeners array. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependOnceListener + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Remove a listener from the listener array for the specified event. + * Caution: Calling this method changes the array indices in the listener array behind the listener. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function removeListener + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ + /** + * Removes all listeners, or those of the specified event. + * @param { string | symbol } [eventType] - The type of the event. + * @return {Promise.} + * @function removeAllListeners + * @memberof ExternalApplication + * @instance + * @tutorial ExternalApplication.EventEmitter + */ /** * Retrieves information about the external application. * @return {Promise.} diff --git a/types/openfin/_v2/api/frame/frame.d.ts b/types/openfin/_v2/api/frame/frame.d.ts index 8795ae190b..2a1b4aa735 100644 --- a/types/openfin/_v2/api/frame/frame.d.ts +++ b/types/openfin/_v2/api/frame/frame.d.ts @@ -46,13 +46,91 @@ export default class _FrameModule extends Base { } /** * @classdesc Represents a way to interact with `iframes`. Facilitates discovery of current context - * (iframe or main window) as well as the ability to listen for frame-specific events. + * (iframe or main window) as well as the ability to listen for frame-specific events. * @class * @alias Frame + * @hideconstructor */ export declare class _Frame extends EmitterBase { identity: Identity; constructor(wire: Transport, identity: Identity); + /** + * Adds the listener function to the end of the listeners array for the specified event type. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function addListener + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function on + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function once + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependListener + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * The listener is added to the beginning of the listeners array. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependOnceListener + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Remove a listener from the listener array for the specified event. + * Caution: Calling this method changes the array indices in the listener array behind the listener. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function removeListener + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ + /** + * Removes all listeners, or those of the specified event. + * @param { string | symbol } [eventType] - The type of the event. + * @return {Promise.} + * @function removeAllListeners + * @memberof Frame + * @instance + * @tutorial Frame.EventEmitter + */ /** * Returns a frame info object for the represented frame * @return {Promise.} diff --git a/types/openfin/_v2/api/interappbus/channel/channel.d.ts b/types/openfin/_v2/api/interappbus/channel/channel.d.ts index 1c9a502e12..bce67e9aed 100644 --- a/types/openfin/_v2/api/interappbus/channel/channel.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/channel.d.ts @@ -12,6 +12,7 @@ export interface ChannelMessagePayload extends Identity { payload: any; } export declare class ChannelBase { + protected removeChannel: (mapKey: string) => void; protected subscriptions: any; defaultAction: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any; private preAction; @@ -20,10 +21,11 @@ export declare class ChannelBase { private defaultSet; protected send: (to: Identity, action: string, payload: any) => Promise>; protected providerIdentity: ProviderIdentity; + protected sendRaw: Transport['sendAction']; constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); processAction(action: string, payload: any, senderIdentity: ProviderIdentity): Promise; beforeAction(func: Action): void; - onError(func: (e: any, action: string, id: Identity) => any): void; + onError(func: (action: string, error: any, id: Identity) => any): void; afterAction(func: Action): void; remove(action: string): void; setDefaultAction(func: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any): void; diff --git a/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts b/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts new file mode 100644 index 0000000000..fed5208e2e --- /dev/null +++ b/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts @@ -0,0 +1,266 @@ +declare const InterApplicationBus: any; +/** + * Instance created to enable use of a channel as a provider. Allows for communication with the {@link Channel#ChannelClient ChannelClients} by invoking an action on + * a single client via {@link Channel#ChannelProvider#dispatch dispatch} or all clients via {@link Channel#ChannelProvider#publish publish} + * and to listen for communication from clients by registering an action via {@link Channel#ChannelProvider#register register}. + * + * ##### Constructor + * + * Returned by {@link Channel.create Channel.create}. + * + * ##### Synchronous Methods + * * {@link Channel#ChannelProvider#destroy destroy()} + * * {@link Channel#ChannelProvider#publish publish(action, payload)} + * * {@link Channel#ChannelProvider#register register(action, listener)} + * * {@link Channel#ChannelProvider#remove remove(action)} + * + * ##### Asynchronous Methods + * * {@link Channel#ChannelProvider#dispatch dispatch(to, action, payload)} + * + * ##### Middleware + * Middleware functions receive the following arguments: (action, payload, senderId). + * The return value of the middleware function will be passed on as the payload from beforeAction, to the action listener, to afterAction + * unless it is undefined, in which case the most recently defined payload is used. Middleware can be used for side effects. + * * {@link Channel#ChannelProvider#setDefaultAction setDefaultAction(middleware)} + * * {@link Channel#ChannelProvider#onError onError(middleware)} + * * {@link Channel#ChannelProvider#beforeAction beforeAction(middleware)} + * * {@link Channel#ChannelProvider#afterAction afterAction(middleware)} + * + * @memberof! Channel# + * @hideconstructor + */ +declare class ChannelProvider { + constructor(); + /** + * + * Destroy the channel. + * @returns {Promise} + */ + destroy(): void; + /** + * + * Dispatch an action to a specified client. Returns a promise for the result of executing that action on the client side. + * @param {Identity} to - Identity of the target client. + * @param {string} action - Name of the action to be invoked by the client. + * @param {*} payload - Payload to be sent along with the action. + * @returns {Promise} + * @tutorial Channel.tutorial + */ + dispatch(): void; + /** + * + * Register an action to be called + * @param {string} action - Name of the action to be registered for channel clients to later invoke. + * @param {Action} listener - Function representing the action to be taken on a client dispatch. + * @returns {boolean} - Boolean representing the successful registration of the action. + * @tutorial Channel.tutorial + */ + register(): void; + /** + * + * Publish an action and payload to every connected client. + * Synchronously returns an array of promises for each action (see dispatch). + * @param {string} action + * @param {*} payload + * @tutorial Channel.tutorial + */ + publish(): void; + /** + * + * Register a listener that is called on every new client connection. + * It is passed the identity of the connecting client and a payload if it was provided to {@link Channel.connect}. + * If you wish to reject the connection, throw an error. Be sure to synchronously provide an onConnection upon receipt of the channelProvider + * to ensure all potential client connections are caught by the listener. + * @param {Channel#ChannelProvider~ConnectionListener} listener + * @tutorial Channel.tutorial + */ + onConnection(): void; + /** + * + * Register a listener that is called on every new client disconnection. + * It is passed the disconnection event of the disconnecting client. + * @param {Channel~ConnectionEvent} listener + * @tutorial Channel.tutorial + */ + onDisconnection(): void; + /** + * + * Register middleware that fires before the action. + * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed before invoking the action. + * @tutorial Channel.middleware + */ + beforeAction(): void; + /** + * + * Register an error handler. This is called before responding on any error. + * @param {function} middleware - Function to be executed in case of an error. + * @tutorial Channel.middleware + */ + onError(): void; + /** + * + * Register middleware that fires after the action. This is passed the return value of the action. + * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed after invoking the action. + * @tutorial Channel.middleware + */ + afterAction(): void; + /** + * + * Remove an action by action name. + * @param {string} action - Name of the action to be removed. + * @tutorial Channel.tutorial + */ + remove(): void; + /** + * + * Sets a default action. This is used any time an action that has not been registered is invoked. + * Default behavior if not set is to throw an error. + * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed when a client invokes an action name that has not been registered. + * @tutorial Channel.middleware + */ + setDefaultAction(): void; +} +/** + * Instance created to enable use of a channel as a client. Allows for communication with the + * {@link Channel#ChannelProvider ChannelProvider} by invoking an action on the + * provider via {@link Channel#ChannelClient#dispatch dispatch} and to listen for communication + * from the provider by registering an action via {@link Channel#ChannelClient#register register}. + * + * ##### Constructor + * Returned by {@link Channel.connect Channel.connect}. + * + * ##### Synchronous Methods + * * {@link Channel#ChannelClient#disconnect disconnect()} + * * {@link Channel#ChannelClient#register register(action, listener)} + * * {@link Channel#ChannelClient#remove remove(action)} + * + * ##### Asynchronous Methods + * * {@link Channel#ChannelClient#dispatch dispatch(to, action, payload)} + * + * ##### Middleware + * Middleware functions receive the following arguments: (action, payload, senderId). + * The return value of the middleware function will be passed on as the payload from beforeAction, to the action listener, to afterAction + * unless it is undefined, in which case the original payload is used. Middleware can be used for side effects. + * * {@link Channel#ChannelClient#setDefaultAction setDefaultAction(middleware)} + * * {@link Channel#ChannelClient#onError onError(middleware)} + * * {@link Channel#ChannelClient#beforeAction beforeAction(middleware)} + * * {@link Channel#ChannelClient#afterAction afterAction(middleware)} + * + * @hideconstructor + * @memberof! Channel# + */ +declare class ChannelClient { + constructor(); + /** + * + * Disconnect from the channel. + * @returns {Promise} + */ + disconnect(): void; + /** + * + * Dispatch the given to the channel provider. Returns a promise that resolves with the response from the provider for that action. + * @param {string} action - Name of the action to be invoked by the channel provider. + * @param {*} payload - Payload to be sent along with the action. + * @tutorial Channel.tutorial + * @returns {Promise} + */ + dispatch(): void; + /** + * + * Register an action to be called by the provider of the channel. + * @param {string} action - Name of the action to be registered for the channel provider to later invoke. + * @param {Action} listener - Function representing the action to be taken on a provider dispatch. + * @tutorial Channel.tutorial + */ + register(): void; + /** + * + * Register middleware that fires before the action. + * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed before invoking the action. + * @tutorial Channel.middleware + */ + beforeAction(): void; + /** + * + * Register a listener that is called on channel disconnection. + * It is passed the disconnection event of the disconnecting channel. + * @param {Channel~ConnectionEvent} listener + * @tutorial Channel.tutorial + */ + onDisconnection(): void; + /** + * Register an error handler. This is called before responding on any error. + * @param {function} middleware - Function to be executed in case of an error. + * @tutorial Channel.middleware + */ + onError(): void; + /** + * + * Register middleware that fires after the action. This is passed the return value of the action. + * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed after invoking the action. + * @tutorial Channel.middleware + */ + afterAction(): void; + /** + * + * Remove an action by action name. + * @param {string} action - Name of the action to be removed. + * @tutorial Channel.tutorial + */ + remove(): void; + /** + * + * Sets a default action. This is used any time an action that has not been registered is invoked. + * Default behavior if not set is to throw an error. + * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed when a client invokes an action name that has not been registered. + * @tutorial Channel.middleware + */ + setDefaultAction(): void; +} +/** + * Channel action callback signature + * @callback Channel#ChannelProvider~Action + * @param {*} payload - Payload sent along with the message. + * @param {Identity} identity - Identity of the sender. +*/ +/** + * Channel action callback signature + * @callback Channel#ChannelClient~Action + * @param {*} payload - Payload sent along with the message. + * @param {Identity} identity - Identity of the sender. +*/ +/** + * Middleware function signature + * @callback Channel#ChannelProvider~Middleware + * @param {string} action - Action to be invoked. + * @param {*} payload - Payload sent along with the message (or error for error middleware). + * @param {Identity} identity - Identity of the sender. +*/ +/** + * Middleware function signature + * @callback Channel#ChannelClient~Middleware + * @param {string} action - Action to be invoked. + * @param {*} payload - Payload sent along with the message. + * @param {Identity} identity - Identity of the sender. +*/ +/** + * Callback for the channel onConnection or onDisconnection. If it errors connection will be rejected. + * @callback Channel#ChannelProvider~ConnectionListener + * @param {Identity} identity - Identity of the client attempting to connect to the channel. + * @param {*} payload - Payload sent with connection request. +*/ +/** + * Callback for onChannelConnect or onChannelDisconnect. + * @typedef {object} Channel~ConnectionEvent + * @property {string} channelId - Identifier of the channel. + * @property {string} uuid - Channel provider uuid. + * @property {string} [name] - Channel provider name. + * @property {string} channelName - Name of the channel. + */ +/** + * @typedef {object} Channel~ConnectOptions + * @property {*} [payload] - Payload to pass to ChannelProvider onConnection action. + * @property {boolean} [wait=true] - If true will wait for ChannelProvider to connect. If false will fail if ChannelProvider is not found. + * + */ diff --git a/types/openfin/_v2/api/interappbus/channel/client.d.ts b/types/openfin/_v2/api/interappbus/channel/client.d.ts index d1c128a349..65b72283ad 100644 --- a/types/openfin/_v2/api/interappbus/channel/client.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/client.d.ts @@ -1,6 +1,11 @@ import { ChannelBase, ProviderIdentity } from './channel'; import Transport from '../../../transport/transport'; +declare type DisconnectionListener = (providerIdentity: ProviderIdentity) => any; export declare class ChannelClient extends ChannelBase { + private disconnectListener; constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); dispatch(action: string, payload?: any): Promise; + onDisconnection(listener: DisconnectionListener): void; + disconnect(): Promise; } +export {}; diff --git a/types/openfin/_v2/api/interappbus/channel/index.d.ts b/types/openfin/_v2/api/interappbus/channel/index.d.ts index 2b2d963932..5d4ce0ff8b 100644 --- a/types/openfin/_v2/api/interappbus/channel/index.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/index.d.ts @@ -26,6 +26,7 @@ export declare class Channel extends EmitterBase { onChannelDisconnect(listener: (...args: any[]) => void): Promise; connect(channelName: string, options?: ConnectOptions): Promise; create(channelName: string): Promise; + protected removeChannelFromMap(mapKey: string): void; onmessage: (msg: ChannelMessage) => boolean; private processChannelMessage; private processChannelConnection; diff --git a/types/openfin/_v2/api/interappbus/channel/provider.d.ts b/types/openfin/_v2/api/interappbus/channel/provider.d.ts index 4b978c2781..569f824a8d 100644 --- a/types/openfin/_v2/api/interappbus/channel/provider.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/provider.d.ts @@ -2,6 +2,7 @@ import { ChannelBase, ProviderIdentity } from './channel'; import Transport from '../../../transport/transport'; import { Identity } from '../../../main'; export declare type ConnectionListener = (identity: Identity, connectionMessage?: any) => any; +export declare type DisconnectionListener = (identity: Identity) => any; export declare class ChannelProvider extends ChannelBase { private connectListener; private disconnectListener; @@ -11,5 +12,6 @@ export declare class ChannelProvider extends ChannelBase { processConnection(senderId: Identity, payload: any): Promise; publish(action: string, payload: any): Promise[]; onConnection(listener: ConnectionListener): void; - onDisconnection(listener: ConnectionListener): void; + onDisconnection(listener: DisconnectionListener): void; + destroy(): Promise; } diff --git a/types/openfin/_v2/api/interappbus/interappbus.d.ts b/types/openfin/_v2/api/interappbus/interappbus.d.ts index 48aaf7430c..12fa146fe4 100644 --- a/types/openfin/_v2/api/interappbus/interappbus.d.ts +++ b/types/openfin/_v2/api/interappbus/interappbus.d.ts @@ -32,7 +32,7 @@ export default class InterApplicationBus extends Base { publish(topic: string, message: any): Promise; /** * Sends a message to a specific application on a specific topic. - * @param { object } destination The uuid of the application to which the message is sent + * @param { Identity } destination The uuid of the application to which the message is sent * @param { string } topic The topic on which the message is sent * @param { any } message The message to be sent. Can be either a primitive data * type (string, number, or boolean) or composite data type (object, array) that diff --git a/types/openfin/_v2/api/notification/notification.d.ts b/types/openfin/_v2/api/notification/notification.d.ts index 9a6bee7076..ae4e2a3d16 100644 --- a/types/openfin/_v2/api/notification/notification.d.ts +++ b/types/openfin/_v2/api/notification/notification.d.ts @@ -22,6 +22,7 @@ export interface NotificationCallback { * are controlled by the runtime. * @class * @alias Notification + * @hideconstructor */ export declare class _Notification extends EmitterBase { private listenerList; @@ -56,6 +57,9 @@ export declare class _Notification extends EmitterBase { */ close(): Promise; } +/** + * @lends Notification + */ export default class _NotificationModule extends Base { private nextNoteId; private genNoteId; @@ -66,5 +70,12 @@ export default class _NotificationModule extends Base { click: string; message: string; }; + /** + * Creates a new Notification. + * @param { object } options + * @return {_Notification} + * @tutorial Notification.create + * @static + */ create(options: any): _Notification; } diff --git a/types/openfin/_v2/api/system/monitor.d.ts b/types/openfin/_v2/api/system/monitor.d.ts index ea4aed799c..2ae54fdf13 100644 --- a/types/openfin/_v2/api/system/monitor.d.ts +++ b/types/openfin/_v2/api/system/monitor.d.ts @@ -15,7 +15,7 @@ export interface MonitorDetails { displayDeviceActive: boolean; deviceScaleFactor: number; monitorRect: Rect; - name: number; + name: string; dpi: Point; monitor: DipScaleRects; } diff --git a/types/openfin/_v2/api/system/system.d.ts b/types/openfin/_v2/api/system/system.d.ts index 76f244cabf..bbaabe5f43 100644 --- a/types/openfin/_v2/api/system/system.d.ts +++ b/types/openfin/_v2/api/system/system.d.ts @@ -22,29 +22,29 @@ import { CrashReporterOption } from './crashReporterOption'; import { SystemEvents } from '../events/system'; /** * AppAssetInfo interface - * @typedef { Object } AppAssetInfo + * @typedef { object } AppAssetInfo * @property { string } src The URL to a zip file containing the package files (executables, dlls, etc…) * @property { string } alias The name of the asset * @property { string } version The version of the package * @property { string } target Specify default executable to launch. This option can be overridden in launchExternalProcess - * @property { args } args The default command line arguments for the aforementioned target. + * @property { string } args The default command line arguments for the aforementioned target. * @property { boolean } mandatory When set to true, the app will fail to load if the asset cannot be downloaded. * When set to false, the app will continue to load if the asset cannot be downloaded. (Default: true) */ /** * AppAssetRequest interface - * @typedef { Object } AppAssetRequest + * @typedef { object } AppAssetRequest * @property { string } alias The name of the asset */ /** * ApplicationInfo interface - * @typedef { Object } ApplicationInfo + * @typedef { object } ApplicationInfo * @property { boolean } isRunning true when the application is running * @property { string } uuid uuid of the application * @property { string } parentUuid uuid of the application that launches this application */ /** - * @typedef { Object } ClearCacheOption + * @typedef { object } ClearCacheOption * @summary Clear cache options. * @desc These are the options required by the clearCache function. * @@ -55,33 +55,45 @@ import { SystemEvents } from '../events/system'; */ /** * CookieInfo interface - * @typedef { Object } CookieInfo + * @typedef { object } CookieInfo * @property { string } name The name of the cookie * @property { string } domain The domain of the cookie * @property { string } path The path of the cookie */ /** * CookieOption interface - * @typedef { Object } CookieOption + * @typedef { object } CookieOption * @property { string } name The name of the cookie */ /** * CpuInfo interface - * @typedef { Object } CpuInfo + * @typedef { object } CpuInfo * @property { string } model The model of the cpu * @property { number } speed The number in MHz * @property { Time } times The numbers of milliseconds the CPU has spent in different modes. */ /** * CrashReporterOption interface -* @typedef { Object } CrashReporterOption +* @typedef { object } CrashReporterOption * @property { boolean } diagnosticMode In diagnostic mode the crash reporter will send diagnostic logs to * the OpenFin reporting service on runtime shutdown * @property { boolean } isRunning check if it's running */ +/** + * DipRect interface + * @typedef { object } DipRect + * @property { Rect } dipRect The DIP coordinates + * @property { Rect } scaledRect The scale coordinates + */ +/** + * DipScaleRects interface + * @typedef { object } DipScaleRects + * @property { Rect } dipRect The DIP coordinates + * @property { Rect } scaledRect The scale coordinates + */ /** * DownloadPreloadInfo interface - * @typedef { Object } DownloadPreloadInfo + * @typedef { object } DownloadPreloadInfo * @desc downloadPreloadScripts function return value * @property { string } url url to the preload script * @property { string } error error during preload script acquisition @@ -89,52 +101,65 @@ import { SystemEvents } from '../events/system'; */ /** * DownloadPreloadOption interface - * @typedef { Object } DownloadPreloadOption + * @typedef { object } DownloadPreloadOption * @desc These are the options object required by the downloadPreloadScripts function * @property { string } url url to the preload script */ /** * Entity interface - * @typedef { Object } Entity + * @typedef { object } Entity * @property { string } type The type of the entity * @property { string } uuid The uuid of the entity */ /** * EntityInfo interface - * @typedef { Object } EntityInfo + * @typedef { object } EntityInfo * @property { string } name The name of the entity * @property { string } uuid The uuid of the entity * @property { Identity } parent The parent of the entity * @property { string } entityType The type of the entity */ +/** + * ExternalApplicationInfo interface + * @typedef { object } ExternalApplicationInfo + * @property { Identity } parent The parent identity + */ /** * ExternalConnection interface - * @typedef { Object } ExternalConnection + * @typedef { object } ExternalConnection * @property { string } token The token to broker an external connection * @property { string } uuid The uuid of the external connection */ /** * ExternalProcessRequestType interface - * @typedef { Object } ExternalProcessRequestType + * @typedef { object } ExternalProcessRequestType * @property { string } path The file path to where the running application resides * @property { string } arguments The argument passed to the running application - * @property { Object } listener This is described in the {LaunchExternalProcessListner} type definition + * @property { LaunchExternalProcessListener } listener This is described in the {LaunchExternalProcessListner} type definition + */ +/** + * FrameInfo interface + * @typedef { object } FrameInfo + * @property { string } name The name of the frame + * @property { string } uuid The uuid of the frame + * @property { entityType } entityType The entity type, could be 'window', 'iframe', 'external connection' or 'unknown' + * @property { Identity } parent The parent identity */ /** * GetLogRequestType interface - * @typedef { Object } GetLogRequestType + * @typedef { object } GetLogRequestType * @property { string } name The name of the running application * @property { number } endFile The file length of the log file * @property { number } sizeLimit The set size limit of the log file */ /** * GpuInfo interface - * @typedef { Object } GpuInfo + * @typedef { object } GpuInfo * @property { string } name The graphics card name */ /** * HostSpecs interface - * @typedef { Object } HostSpecs + * @typedef { object } HostSpecs * @property { boolean } aeroGlassEnabled Value to check if Aero Glass theme is supported on Windows platforms * @property { string } arch "x86" for 32-bit or "x86_64" for 64-bit * @property { Array } cpus The same payload as Node's os.cpus() @@ -145,17 +170,41 @@ import { SystemEvents } from '../events/system'; */ /** * Identity interface - * @typedef { Object } Identity + * @typedef { object } Identity * @property { string } name The name of the application * @property { string } uuid The uuid of the application */ /** * LogInfo interface - * @typedef { Object } LogInfo + * @typedef { object } LogInfo * @property { string } name The filename of the log * @property { number } size The size of the log in bytes * @property { string } date The unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)"" */ +/** + * MonitorDetails interface + * @typedef { object } MonitorDetails + * @property { DipScaleRects } available The available DIP scale coordinates + * @property { Rect } availableRect The available monitor coordinates + * @property { string } deviceId The device id of the display + * @property { boolean } displayDeviceActive true if the display is active + * @property { number } deviceScaleFactor The device scale factor + * @property { Rect } monitorRect The monitor coordinates + * @property { string } name The name of the display + * @property { Point } dpi The dots per inch + * @property { DipScaleRects } monitor The monitor coordinates + */ +/** + * MonitorInfo interface + * @typedef { object } MonitorInfo + * @property { number } deviceScaleFactor The device scale factor + * @property { Point } dpi The dots per inch + * @property { Array } nonPrimaryMonitors The array of monitor details + * @property { MonitorDetails } primaryMonitor The monitor details + * @property { string } reason always "api-query" + * @property { TaskBar } taskBar The taskbar on monitor + * @property { DipRect } virtualScreen The virtual display screen coordinates + */ /** * @typedef { verbose | info | warning | error | fatal } LogLevel * @summary Log verbosity levels. @@ -169,13 +218,19 @@ import { SystemEvents } from '../events/system'; */ /** * PointTopLeft interface - * @typedef { Object } PointTopLeft + * @typedef { object } PointTopLeft * @property { number } top The mouse top position in virtual screen coordinates * @property { number } left The mouse left position in virtual screen coordinates */ +/** + * Point interface + * @typedef { object } Point + * @property { number } x The mouse x position + * @property { number } y The mouse y position + */ /** * ProcessInfo interface - * @typedef { Object } ProcessInfo + * @typedef { object } ProcessInfo * @property { numder } cpuUsage The percentage of total CPU usage * @property { string } name The application name * @property { number } nonPagedPoolUsage The current nonpaged pool usage in bytes @@ -192,28 +247,36 @@ import { SystemEvents } from '../events/system'; */ /** * ProxyConfig interface - * @typedef { Object } ProxyConfig + * @typedef { object } ProxyConfig * @property { string } proxyAddress The configured proxy address * @property { numder } proxyPort The configured proxy port * @property { string } type The proxy Type */ /** * ProxyInfo interface - * @typedef { Object } ProxyInfo + * @typedef { object } ProxyInfo * @property { ProxyConfig } config The proxy config * @property { ProxySystemInfo } system The proxy system info */ /** * ProxySystemInfo interface - * @typedef { Object } ProxySystemInfo + * @typedef { object } ProxySystemInfo * @property { string } autoConfigUrl The auto configuration url * @property { string } bypass The proxy bypass info * @property { boolean } enabled Value to check if a proxy is enabled * @property { string } proxy The proxy info */ +/** + * Rect interface + * @typedef { object } Rect + * @property { number } bottom The bottom-most coordinate + * @property { nubmer } left The left-most coordinate + * @property { number } right The right-most coordinate + * @property { nubmer } top The top-most coordinate + */ /** * RegistryInfo interface - * @typedef { Object } RegistryInfo + * @typedef { object } RegistryInfo * @property { any } data The registry data * @property { string } rootKey The registry root key * @property { string } subkey The registry key @@ -222,13 +285,22 @@ import { SystemEvents } from '../events/system'; */ /** * RuntimeDownloadOptions interface - * @typedef { Object } RuntimeDownloadOptions + * @typedef { object } RuntimeDownloadOptions * @desc These are the options object required by the downloadRuntime function. * @property { string } version The given version to download */ +/** + * RuntimeInfo interface + * @typedef { object } RuntimeInfo + * @property { string } architecture The runtime build architecture + * @property { string } manifestUrl The runtime manifest URL + * @property { nubmer } port The runtime websocket port + * @property { string } securityRealm The runtime security realm + * @property { string } version The runtime version + */ /** * RVMInfo interface - * @typedef { Object } RVMInfo + * @typedef { object } RVMInfo * @property { string } action The name of action: "get-rvm-info" * @property { string } appLogDirectory The app log directory * @property { string } path The path of OpenfinRVM.exe @@ -236,25 +308,51 @@ import { SystemEvents } from '../events/system'; * @property { string } version The version of RVM * @property { string } 'working-dir' The working directory */ +/** + * ShortCutConfig interface + * @typedef { object } ShortCutConfig + * @property { boolean } desktop true if application has a shortcut on the desktop + * @property { boolean } startMenu true if application has shortcut in the start menu + * @property { boolean } systemStartup true if application will be launched on system startup + */ +/** + * SubOptions interface + * @typedef { Object } SubOptions + * @property { number } timestamp The event timestamp + */ +/** + * TaskBar interface + * @typedef { object } TaskBar + * @property { string } edge which edge of a monitor the taskbar is on + * @property { Rect } rect The taskbar coordinates + */ /** * TerminateExternalRequestType interface - * @typedef { Object } TerminateExternalRequestType + * @typedef { object } TerminateExternalRequestType * @property { string } uuid The uuid of the running application * @property { number } timeout Time out period before the running application terminates * @property { boolean } killtree Value to terminate the running application */ /** * Time interface - * @typedef { Object } Time + * @typedef { object } Time * @property { number } user The number of milliseconds the CPU has spent in user mode * @property { number } nice The number of milliseconds the CPU has spent in nice mode * @property { number } sys The number of milliseconds the CPU has spent in sys mode * @property { number } idle The number of milliseconds the CPU has spent in idle mode * @property { number } irq The number of milliseconds the CPU has spent in irq mode */ +/** + * TrayInfo interface + * @typedef { object } TrayInfo + * @property { Bounds } bounds The bound of tray icon in virtual screen pixels + * @property { MonitorInfo } monitorInfo Please see fin.System.getMonitorInfo for more information + * @property { number } x copy of bounds.x + * @property { number } y copy of bounds.y + */ /** * WindowDetail interface - * @typedef { Object } WindowDetail + * @typedef { object } WindowDetail * @property { number } bottom The bottom-most coordinate of the window * @property { number } height The height of the window * @property { boolean } isShowing Value to check if the window is showing @@ -267,7 +365,7 @@ import { SystemEvents } from '../events/system'; */ /** * WindowInfo interface - * @typedef { Object } WindowInfo + * @typedef { object } WindowInfo * @property { Array } childWindows The array of child windows details * @property { WindowDetail } mainWindow The main window detail * @property { string } uuid The uuid of the application @@ -275,11 +373,89 @@ import { SystemEvents } from '../events/system'; /** * An object representing the core of OpenFin Runtime. Allows the developer * to perform system-level actions, such as accessing logs, viewing processes, - * clearing the cache and exiting the runtime. + * clearing the cache and exiting the runtime as well as listen to system events. * @namespace */ export default class System extends EmitterBase { constructor(wire: Transport); + private sendExternalProcessRequest; + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function addListener + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function on + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function once + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependListener + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * The listener is added to the beginning of the listeners array. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependOnceListener + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Remove a listener from the listener array for the specified event. + * Caution: Calling this method changes the array indices in the listener array behind the listener. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function removeListener + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ + /** + * Removes all listeners, or those of the specified event. + * @param { string | symbol } [eventType] - The type of the event. + * @return {Promise.} + * @function removeAllListeners + * @memberof System + * @instance + * @tutorial System.EventEmitter + */ /** * Returns the version of the runtime. The version contains the major, minor, * build and revision numbers. diff --git a/types/openfin/_v2/api/window/window.d.ts b/types/openfin/_v2/api/window/window.d.ts index fcefc4fa5d..14ac2bf320 100644 --- a/types/openfin/_v2/api/window/window.d.ts +++ b/types/openfin/_v2/api/window/window.d.ts @@ -7,6 +7,7 @@ import Transport from '../../transport/transport'; import { WindowEvents } from '../events/window'; import { AnchorType } from './anchor-type'; import { WindowOption } from './windowOption'; +import { EntityType } from '../frame/frame'; /** * @lends Window */ @@ -29,7 +30,7 @@ export default class _WindowModule extends Base { wrapSync(identity: Identity): _Window; /** * Creates a new Window. - * @param { WindowOption } options - Window creation options + * @param { Window~options } options - Window creation options * @return {Promise.<_Window>} * @tutorial Window.create * @static @@ -66,7 +67,7 @@ export interface WindowInfo { export interface FrameInfo { name: string; uuid: string; - entityType: string; + entityType: EntityType; parent?: Identity; } export interface Area { @@ -75,6 +76,203 @@ export interface Area { x: number; y: number; } +/** + * @typedef {object} Window~options + * @summary Window creation options. + * @desc This is the options object required by {@link Window.create Window.create}. + * + * Note that `name` is the only required property — albeit the `url` property is usually provided as well + * (defaults to `"about:blank"` when omitted). + * + * _This jsdoc typedef mirrors the `WindowOptions` TypeScript interface in `@types/openfin`._ + * + * @property {object} [accelerator] + * Enable keyboard shortcuts for devtools, zoom, reload, and reload ignoring cache. + * + * @property {boolean} [accelerator.devtools=false] + * If `true`, enables the devtools keyboard shortcut:
    + * `Ctrl` + `Shift` + `I` _(Toggles Devtools)_ + * + * @property {boolean} [accelerator.reload=false] + * If `true`, enables the reload keyboard shortcuts:
    + * `Ctrl` + `R` _(Windows)_
    + * `F5` _(Windows)_
    + * `Command` + `R` _(Mac)_ + * + * @property {boolean} [accelerator.reloadIgnoringCache=false] + * If `true`, enables the reload-from-source keyboard shortcuts:
    + * `Ctrl` + `Shift` + `R` _(Windows)_
    + * `Shift` + `F5` _(Windows)_
    + * `Command` + `Shift` + `R` _(Mac)_ + * + * @property {boolean} [accelerator.zoom=false] + * If `true`, enables the zoom keyboard shortcuts:
    + * `Ctrl` + `+` _(Zoom In)_
    + * `Ctrl` + `Shift` + `+` _(Zoom In)_
    + * `Ctrl` + `-` _(Zoom Out)_
    + * `Ctrl` + `Shift` + `-` _(Zoom Out)_
    + * `Ctrl` + `Scroll` _(Zoom In & Out)_
    + * `Ctrl` + `0` _(Restore to 100%)_ + * + * @property {boolean} [alwaysOnTop=false] - _Updatable._ + * A flag to always position the window at the top of the window stack. + * + * @property {object} [api] + * Configurations for API injection. + * + * @property {object} [api.iframe] Configure if the the API should be injected into iframes based on domain. + * + * @property {boolean} [api.iframe.crossOriginInjection=false] Controls if the `fin` API object is present for cross origin iframes. + * @property {boolean} [api.iframe.sameOriginInjection=true] Controls if the `fin` API object is present for same origin iframes. + * + * @property {number} [aspectRatio=0] - _Updatable._ + * The aspect ratio of width to height to enforce for the window. If this value is equal to or less than zero, + * an aspect ratio will not be enforced. + * + * @property {boolean} [autoShow=true] + * A flag to automatically show the window when it is created. + * + * @property {string} [backgroundColor="#FFF"] + * The window’s _backfill_ color as a hexadecimal value. Not to be confused with the content background color + * (`document.body.style.backgroundColor`), + * this color briefly fills a window’s (a) content area before its content is loaded as well as (b) newly exposed + * areas when growing a window. Setting + * this value to the anticipated content background color can help improve user experience. + * Default is white. + * + * @property {object} [contentNavigation] + * Restrict navigation to URLs that match a whitelisted pattern. See [here](https://developer.chrome.com/extensions/match_patterns) + * for more details. + * @property {string[]} [contentNavigation.whitelist=[]] List of whitelisted URLs. + * + * @property {boolean} [contextMenu=true] - _Updatable._ + * A flag to show the context menu when right-clicking on a window. + * Gives access to the devtools for the window. + * + * @property {object} [cornerRounding] - _Updatable._ + * Defines and applies rounded corners for a frameless window. **NOTE:** On macOS corner is not ellipse but circle rounded by the + * average of _height_ and _width_. + * @property {number} [cornerRounding.height=0] The height in pixels. + * @property {number} [cornerRounding.width=0] The width in pixels. + * + * @property {string} [customData=""] - _Updatable._ + * A field that the user can attach serializable data to to be ferried around with the window options. + * _When omitted, the default value of this property is the empty string (`""`)._ + * + * @property {customRequestHeaders[]} [customRequestHeaders] + * Defines list of {@link customRequestHeaders} for requests sent by the window. + * + * @property {boolean} [defaultCentered=false] + * Centers the window in the primary monitor. This option overrides `defaultLeft` and `defaultTop`. When `saveWindowState` is `true`, + * this value will be ignored for subsequent launches in favor of the cached value. **NOTE:** On macOS _defaultCenter_ is + * somewhat above center vertically. + * + * @property {number} [defaultHeight=500] + * The default height of the window. When `saveWindowState` is `true`, this value will be ignored for subsequent launches + * in favor of the cached value. + * + * @property {number} [defaultLeft=100] + * The default left position of the window. When `saveWindowState` is `true`, this value will be ignored for subsequent + * launches in favor of the cached value. + * + * @property {number} [defaultTop=100] + * The default top position of the window. When `saveWindowState` is `true`, this value will be ignored for subsequent + * launches in favor of the cached value. + * + * @property {number} [defaultWidth=800] + * The default width of the window. When `saveWindowState` is `true`, this value will be ignored for subsequent + * launches in favor of the cached value. + * + * @property {boolean} [frame=true] - _Updatable._ + * A flag to show the frame. + * + * @hidden-property {boolean} [hideOnClose=false] - A flag to allow a window to be hidden when the close button is clicked. + * + * @property {string} [icon] - _Updatable. Inheritable._ + * A URL for the icon to be shown in the window title bar and the taskbar. + * _When omitted, inherits from the parent application._ + * + * @property {number} [maxHeight=-1] - _Updatable._ + * The maximum height of a window. Will default to the OS defined value if set to -1. + * + * @property {boolean} [maximizable=true] - _Updatable._ + * A flag that lets the window be maximized. + * + * @property {number} [maxWidth=-1] - _Updatable._ + * The maximum width of a window. Will default to the OS defined value if set to -1. + * + * @property {number} [minHeight=0] - _Updatable._ + * The minimum height of a window. + * + * @property {boolean} [minimizable=true] - _Updatable._ + * A flag that lets the window be minimized. + * + * @property {number} [minWidth=0] - _Updatable._ + * The minimum width of a window. + * + * @property {string} name + * The name of the window. + * + * @property {number} [opacity=1.0] - _Updatable._ + * A flag that specifies how transparent the window will be. + * This value is clamped between `0.0` and `1.0`. + * + * @property {preloadScript[]} [preloadScripts] - _Inheritable_ + * A list of scripts that are eval'ed before other scripts in the page. When omitted, _inherits_ + * from the parent application. + * + * @property {boolean} [resizable=true] - _Updatable._ + * A flag to allow the user to resize the window. + * + * @property {object} [resizeRegion] - _Updatable._ + * Defines a region in pixels that will respond to user mouse interaction for resizing a frameless window. + * @property {number} [resizeRegion.bottomRightCorner=9] + * The size in pixels of an additional square resizable region located at the bottom right corner of a frameless window. + * @property {number} [resizeRegion.size=7] + * The size in pixels. + * @property {object} [resizeRegion.sides={top:true,right:true,bottom:true,left:true}] + * Sides that a window can be resized from. + * + * @property {boolean} [saveWindowState=true] + * A flag to cache the location of the window. + * + * @property {boolean} [shadow=false] + * A flag to display a shadow on frameless windows. + * `shadow` and `cornerRounding` are mutually exclusive. + * On Windows 7, Aero theme is required. + * + * @property {boolean} [showTaskbarIcon=true] - _Updatable._ _Windows_. + * A flag to show the window's icon in the taskbar. + * + * @property {boolean} [smallWindow=false] + * A flag to specify a frameless window that can be be created and resized to less than 41x36px (width x height). + * _Note: Caveats of small windows are no Aero Snap and drag to/from maximize._ + * + * @property {string} [state="normal"] + * The visible state of the window on creation. + * One of: + * * `"maximized"` + * * `"minimized"` + * * `"normal"` + * + * @property {string} [taskbarIconGroup=] - _Windows_. + * Specify a taskbar group for the window. + * _If omitted, defaults to app's uuid (`fin.desktop.Application.getCurrent().uuid`)._ + * + * @property {string} [url="about:blank"] + * The URL of the window. + * + * @property {string} [uuid=] + * The `uuid` of the application, unique within the set of all `Application`s running in OpenFin Runtime. + * If omitted, defaults to the `uuid` of the application spawning the window. + * If given, must match the `uuid` of the application spawning the window. + * In other words, the application's `uuid` is the only acceptable value, but is the default, so there's + * really no need to provide it. + * + * @property {boolean} [waitForPageLoad=false] + * When set to `true`, the window will not appear until the `window` object's `load` event fires. + * When set to `false`, the window will appear immediately without waiting for content to be loaded. + */ /** * @typedef { Object } Area * @property { number } height Area's height @@ -117,7 +315,7 @@ this animation onto the end of the animation queue. /** * Bounds is a interface that has the properties of height, * width, left, top which are all numbers - * @typedef { Object } Bounds + * @typedef { object } Bounds * @property { number } height Get the application height bound * @property { number } width Get the application width bound * @property { number } top Get the application top bound @@ -130,337 +328,91 @@ this animation onto the end of the animation queue. * control over the window state such as the ability to minimize, maximize, restore, etc. * By default a window does not show upon instantiation; instead the window's show() method * must be invoked manually. The new window appears in the same process as the parent window. + * It has the ability to listen for window specific events. * @class * @alias Window -*/ + * @hideconstructor + */ export declare class _Window extends EmitterBase { identity: Identity; - /** - * Raised when a window within this application requires credentials from the user. - * - * @event Window#auth-requested - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {object} authInfo - * @property {string} authInfo.host - Host server. - * @property {boolean} authInfo.isProxy - Indicates if the request involves a proxy. - * @property {number} authInfo.port - Port number. - * @property {string} authInfo.realm - Authentication request realm. - * @property {string} authInfo.scheme - Authentication scheme. - */ - /** - * Raised when a window loses focus. - * - * @event Window#blurred - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised after changes in a window's size and/or position. - * - * @event Window#bounds-changed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {number} changeType - Describes what kind of change occurred. - 0 means a change in position. - 1 means a change in size. - 2 means a change in position and size. - * @property {string} deferred - Indicated whether pending changes have been applied. - * @property {number} height - New height of the window. - * @property {number} left - New left most coordinate of the window. - * @property {number} top - New top most coordinate of the window. - * @property {number} width - New width of the window. - */ - /** - * Raised when a window has been prevented from closing. A window will be prevented from closing by default, - either through the API or by a user when ‘close-requested’ has been subscribed to and the Window.close(force) flag is false. - * - * @event Window#close-requested - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window has closed. - * - * @event Window#closed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window has crashed. - * - * @event Window#crashed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when the frame is disabled after all prevent user changes in window's size and/or position have completed. - * - * @event Window#disabled-frame-bounds-changed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {number} changeType - Describes what kind of change occurred. - 0 means a change in position. - 1 means a change in size. - 2 means a change in position and size. - * @property {string} deferred - Indicated whether pending changes have been applied. - * @property {number} height - New height of the window. - * @property {number} left - New left most coordinate of the window. - * @property {number} top - New top most coordinate of the window. - * @property {number} width - New width of the window. - */ - /** - * Raised when the frame is disabled during prevented user changes to a window's size and/or position. - * - * @event Window#disabled-frame-bounds-changing - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {number} changeType - Describes what kind of change occurred. - 0 means a change in position. - 1 means a change in size. - 2 means a change in position and size. - * @property {string} deferred - Indicated whether pending changes have been applied. - * @property {number} height - New height of the window. - * @property {number} left - New left most coordinate of the window. - * @property {number} top - New top most coordinate of the window. - * @property {number} width - New width of the window. - */ - /** - * Raised when the window has been embedded. - * - * @event Window#embedded - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when an external process has exited. - * - * @event Window#external-process-exited - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} processUuid - The process handle UUID. - * @property {number} exitCode - The process exit code - */ - /** - * Raised when an external process has started. - * - * @event Window#external-process-started - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} processUuid - The process handle UUID. - */ - /** - * Raised when a window's frame becomes disabled. - * - * @event Window#frame-disabled - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window's frame becomes enabled. - * - * @event Window#frame-enabled - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window joins/leaves a group and/or when the group a window is a member of changes. - * - * @event Window#group-changed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} source - Which group array the window that the event listener was registered on is included in: - 'source' The window is included in sourceGroup. - 'target' The window is included in targetGroup. - 'nothing' The window is not included in sourceGroup nor targetGroup. - * @property {string} reason - The reason this event was triggered. - 'leave' A window has left the group due to a leave or merge with group. - 'join' A window has joined the group. - 'merge' Two groups have been merged together. - 'disband' There are no other windows in the group. - * @property {string} name - Name of the window. - * @property {legacyWindowIdentity[]} sourceGroup - All the windows in the group the sourceWindow originated from. - * @property {string} sourceWindowAppUuid - UUID of the application the sourceWindow belongs to the - source window is the window in which (merge/join/leave)group(s) was called. - * @property {string} sourceWindowName - Name of the sourcewindow. - The source window is the window in which (merge/join/leave)group(s) was called. - * @property {legacyWindowIdentity[]} targetGroup - All the windows in the group the targetWindow orginated from. - * @property {string} targetWindowAppUuid - UUID of the application the targetWindow belongs to. - The target window is the window that was passed into (merge/join)group(s). - * @property {string} targetWindowName - Name of the targetWindow. - The target window is the window that was passed into (merge/join)group(s). - */ - /** - * Raised when a window has been hidden. - * - * @event Window#hidden - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} reason - Action prompted the close The reasons are: - "hide" - "hide-on-close" - */ - /** - * Raised when a window is initialized. - * - * @event Window#initialized - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window is maximized. - * - * @event Window#maximized - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window is minimized. - * - * @event Window#minimized - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when window navigation is rejected as per ContentNavigation whitelist/blacklist rules. - * - * @event Window#navigation-rejected - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} sourceName - source of navigation window name. - * @property {string} url - Blocked content url. - */ - /** - * Raised when a window is out of memory. - * - * @event Window#out-of-memory - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised after the execution of all of a window's preload scripts. Contains - information about all window's preload scripts' final states. - * - * @event Window#preload-scripts-state-changed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states - */ - /** - * Raised during the execution of a window's preload script. Contains information - about a single window's preload script's state, for which the event has been raised. - * - * @event Window#preload-scripts-state-changing - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states - */ - /** - * Raised when an HTTP load was cancelled or failed. - * - * @event Window#resource-load-failed - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {number} errorCode - The Chromium error code. - * @property {string} errorDescription - The Chromium error description. - * @property {string} validatedURL - The url attempted. - * @property {boolean} isMainFrame - Was the attempt made from the main frame. - */ - /** - * Raised when an HTTP resource request has received response details. - * - * @event Window#resource-response-received - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {boolean} status - Status of the request. - * @property {string} newUrl - The URL of the responded resource. - * @property {string} originalUrl - The requested URL. - * @property {number} httpResponseCode - The HTTP Response code. - * @property {string} requestMethod - The HTTP request method. - * @property {string} referrer - The HTTP referrer. - * @property {object} headers - The HTTP headers. - * @property {string} resourceType - Resource type: - "mainFrame", "subFrame", - "styleSheet", "script", "image", - "object", "xhr", or "other" - */ - /** - * Raised when a window has reloaded. - * - * @event Window#reloaded - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - * @property {string} url - Url has has been reloaded. - */ - /** - * Raised when a window is displayed after having been minimized or - when a window leaves the maximize state without minimizing. - * - * @event Window#restored - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window has been prevented from showing. - A window will be prevented from showing by default, either through the API or by a user when - ‘show-requested’ has been subscribed to on the window or 'window-show-requested' - on the parent application and the Window.show(force) flag is false. - * - * @event Window#show-requested - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * Raised when a window been shown. - * - * @event Window#shown - * @type {object} - * @property {string} name - Name of the window. - * @property {string} uuid - UUID of the application that the window belongs to. - */ - /** - * @typedef {object} legacyWindowIdentity - * @summary Object summary - * @desc Object description - * @property {string} appUuid - The UUID of the application this window entry belongs to. - * @property {string} windowName - The name of this window entry. - */ - /** - * @typedef {object} preloadScriptState - * @summary Object summary - * @desc Object description - * @property {string} url - The url of the preload script. - * @property {string} state - The preload script state: - "load-failed", "failed", "succeeded" - */ constructor(wire: Transport, identity: Identity); + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function addListener + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Adds a listener to the end of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - Called whenever an event of the specified type occurs. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function on + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function once + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependListener + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed. + * The listener is added to the beginning of the listeners array. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function prependOnceListener + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Remove a listener from the listener array for the specified event. + * Caution: Calling this method changes the array indices in the listener array behind the listener. + * @param { string | symbol } eventType - The type of the event. + * @param { Function } listener - The callback function. + * @param { SubOptions } [options] - Option to support event timestamps. + * @return {Promise.} + * @function removeListener + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ + /** + * Removes all listeners, or those of the specified event. + * @param { string | symbol } [eventType] - The type of the event. + * @return {Promise.} + * @function removeAllListeners + * @memberof Window + * @instance + * @tutorial Window.EventEmitter + */ createWindow(options: WindowOption): Promise<_Window>; private windowListFromNameList; /** @@ -518,23 +470,26 @@ export declare class _Window extends EmitterBase { */ close(force?: boolean): Promise; /** - * Returns then running applications uuid + * Returns the native OS level Id. + * In Windows, it will return the Windows [handle](https://docs.microsoft.com/en-us/windows/desktop/WinProg/windows-data-types#HWND). * @return {Promise.} * @tutorial Window.getNativeId */ getNativeId(): Promise; + disableFrame(): Promise; /** * Prevents a user from changing a window's size/position when using the window's frame. * @return {Promise.} - * @tutorial Window.disableFrame + * @tutorial Window.disableUserMovement */ - disableFrame(): Promise; + disableUserMovement(): Promise; + enableFrame(): Promise; /** * Re-enables user changes to a window's size/position when using the window's frame. * @return {Promise.} - * @tutorial Window.enableFrame + * @tutorial Window.enableUserMovement */ - enableFrame(): Promise; + enableUserMovement(): Promise; /** * Executes Javascript on the window, restricted to windows you own or windows owned by * applications you have created. @@ -601,6 +556,12 @@ export declare class _Window extends EmitterBase { * @tutorial Window.getState */ getState(): Promise; + /** + * Determines if the window is a main window. + * @return {boolean} + * @tutorial Window.isMainWindow + */ + isMainWindow(): boolean; /** * Determines if the window is currently showing. * @return {Promise.} @@ -609,7 +570,7 @@ export declare class _Window extends EmitterBase { isShowing(): Promise; /** * Joins the same window group as the specified window. - * @param { class } target The window whose group is to be joined + * @param { _Window } target The window whose group is to be joined * @return {Promise.} * @tutorial Window.joinGroup */ @@ -634,7 +595,7 @@ export declare class _Window extends EmitterBase { maximize(): Promise; /** * Merges the instance's window group with the same window group as the specified window - * @param { class } target The window whose group is to be merged with + * @param { _Window } target The window whose group is to be merged with * @return {Promise.} * @tutorial Window.mergeGroups */ @@ -769,6 +730,12 @@ export declare class _Window extends EmitterBase { * @tutorial Window.navigateBack */ navigateBack(): Promise; + /** + * Navigates the window forward one page. + * @return {Promise.} + * @tutorial Window.navigateForward + */ + navigateForward(): Promise; /** * Stops any current navigation the window is performing. * @return {Promise.} diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index b5d04f1a27..54b5523130 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for OpenFin API 37.0 +// Type definitions for OpenFin API 39.0 // Project: https://openfin.co/ // Definitions by: Chris Barker // Ricardo de Pena @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -// based on v9.61.37.14 +// based on v10.66.39.25 // see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean /** From b95ec122409ba19829979549c7006cfa86c86c2c Mon Sep 17 00:00:00 2001 From: Scott Humphries Date: Tue, 29 Jan 2019 13:12:14 -0600 Subject: [PATCH 176/312] Add jest test to frisby --- types/frisby/frisby-tests.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/frisby/frisby-tests.ts b/types/frisby/frisby-tests.ts index d0bb27ff20..65a7315790 100644 --- a/types/frisby/frisby-tests.ts +++ b/types/frisby/frisby-tests.ts @@ -18,4 +18,9 @@ describe('Test Suite 1', () => { .expect('status', 418) .done(done); }); + + it('should handle jest matchers', () => { + const str = 'bar'; + expect(str).toHaveLength(3); + }); }); From 00b0305f7eeaec761670a202b0d35cf3d9dba9ae Mon Sep 17 00:00:00 2001 From: Vlad Shcherbin Date: Tue, 29 Jan 2019 22:41:56 +0300 Subject: [PATCH 177/312] Add rollup-plugin-delete types --- types/rollup-plugin-delete/index.d.ts | 24 +++++++++++++++++++ types/rollup-plugin-delete/package.json | 7 ++++++ .../rollup-plugin-delete-tests.ts | 13 ++++++++++ types/rollup-plugin-delete/tsconfig.json | 23 ++++++++++++++++++ types/rollup-plugin-delete/tslint.json | 1 + 5 files changed, 68 insertions(+) create mode 100644 types/rollup-plugin-delete/index.d.ts create mode 100644 types/rollup-plugin-delete/package.json create mode 100644 types/rollup-plugin-delete/rollup-plugin-delete-tests.ts create mode 100644 types/rollup-plugin-delete/tsconfig.json create mode 100644 types/rollup-plugin-delete/tslint.json diff --git a/types/rollup-plugin-delete/index.d.ts b/types/rollup-plugin-delete/index.d.ts new file mode 100644 index 0000000000..9f9cfe020d --- /dev/null +++ b/types/rollup-plugin-delete/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for rollup-plugin-delete 0.2 +// Project: https://github.com/vladshcherbin/rollup-plugin-delete#readme +// Definitions by: Vlad Shcherbin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import del = require('del'); +import { Plugin } from 'rollup'; + +export interface Options extends del.Options { + /** + * Patterns of files and folders to be deleted. + * @default [] + */ + readonly targets: ReadonlyArray | string; + + /** + * Outputs removed files and folders to console. + * @default false + */ + readonly verbose?: boolean; +} + +export default function(options?: Options): Plugin; diff --git a/types/rollup-plugin-delete/package.json b/types/rollup-plugin-delete/package.json new file mode 100644 index 0000000000..8daa001274 --- /dev/null +++ b/types/rollup-plugin-delete/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "@types/del": "^3.0.1", + "rollup": ">=0.60.0" + } +} diff --git a/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts b/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts new file mode 100644 index 0000000000..eff3508e29 --- /dev/null +++ b/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts @@ -0,0 +1,13 @@ +import del from 'rollup-plugin-delete'; + +del(); // $ExpectType Plugin + +del({}); // $ExpectError + +del({ targets: '/dist' }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true, dryRun: true }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true, dryRun: true, debug: true }); // $ExpectType Plugin diff --git a/types/rollup-plugin-delete/tsconfig.json b/types/rollup-plugin-delete/tsconfig.json new file mode 100644 index 0000000000..d03999e03a --- /dev/null +++ b/types/rollup-plugin-delete/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", + "rollup-plugin-delete-tests.ts" + ] +} diff --git a/types/rollup-plugin-delete/tslint.json b/types/rollup-plugin-delete/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-delete/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b9ac343d1126748daa40c57d0c797d8416bb1a71 Mon Sep 17 00:00:00 2001 From: Vlad Shcherbin Date: Tue, 29 Jan 2019 23:19:55 +0300 Subject: [PATCH 178/312] Remove @types dependency from package.json --- types/rollup-plugin-delete/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/types/rollup-plugin-delete/package.json b/types/rollup-plugin-delete/package.json index 8daa001274..272f65edde 100644 --- a/types/rollup-plugin-delete/package.json +++ b/types/rollup-plugin-delete/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "@types/del": "^3.0.1", "rollup": ">=0.60.0" } } From 342dd2a71f1e04f7110def2bce1e8ed988a87f4d Mon Sep 17 00:00:00 2001 From: licui Date: Tue, 29 Jan 2019 15:46:51 -0500 Subject: [PATCH 179/312] Add missing API functions in Application --- types/openfin/index.d.ts | 26 ++++++++++++++++++++---- types/openfin/openfin-tests.ts | 36 ++++++++++++++++++++++++++++++---- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 54b5523130..559a6318b3 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -37,6 +37,7 @@ declare namespace fin { // v2 shapes type Identity = import('./_v2/identity').Identity; + type applicationLogInfo = import('./_v2/api/application/application').LogInfo; type LaunchInfo = import('./_v2/api/application/application').ApplicationInfo; type ShortCutConfig = import('./_v2/api/application/application').ShortCutConfig; type TrayInfo = import('./_v2/api/application/application').TrayInfo; @@ -144,6 +145,10 @@ declare namespace fin { * Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows. */ getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves information about the application. + */ + getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest. */ @@ -156,14 +161,14 @@ declare namespace fin { * Retrieves current configuration of application's shortcuts. */ getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void; - /** - * Retrieves information about the application. - */ - getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves information about the system tray. */ getTrayIconInfo(callback?: (trayInfo: TrayInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the current zoom level of the application. + */ + getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void; /** * Determines if the application is currently running. */ @@ -202,6 +207,14 @@ declare namespace fin { * Tells the rvm to relaunch the main application once upon a complete shutdown */ scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sends a message to the RVM to upload the application's logs. On success, an object containing logId is returned. + */ + sendApplicationLog(callback?: (logInfo: applicationLogInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Sets an associated username with that app for Application Log Management use + */ + setAppLogUsername(username: string, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Sets new shortcut configuration for current application. * Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to @@ -212,6 +225,11 @@ declare namespace fin { * Adds a customizable icon in the system tray and notifies the application when clicked. */ setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the zoom level of the application. The original size is 0 and each increment above or below represents zooming 20% + * larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Closes the application by terminating its process. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 5367823dae..134139ce2e 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -56,6 +56,10 @@ function test_application() { ++groupCounter; }); }); + // getInfo + application.getInfo(info => { + console.log(`Launch mode: ${info.launchMode}`); + }); // getManifest application.getManifest(manifest => { console.log("Application manifest:"); @@ -72,15 +76,16 @@ function test_application() { console.log("Start Menu shortcut is enabled: ", config.startMenu); console.log("System Startup shortcut is enabled: ", config.systemStartup); }); - // getInfo - application.getInfo(info => { - console.log(`Launch mode: ${info.launchMode}`); - }); // getTrayIconInfo application.getTrayIconInfo(info => { console.log(info.x, info.y, info.bounds.left, info.bounds.top, info.bounds.height, info.bounds.width, info.monitorInfo.reason); }); + // getZoomLevel + application.getZoomLevel(level => { + console.log("Application zoom level:"); + console.log(level); + }); // isRunning application.isRunning(running => { console.log("the application is", running ? "running" : "not running"); @@ -107,12 +112,29 @@ function test_application() { }, err => { console.log("failure:", err); }); + // run + application.run(() => { + console.log("Application is running."); + }, err => { + console.log("failure:", err); + }); // schedule restart application.scheduleRestart(() => { console.log("You will not read this."); }, err => { console.log("failure:", err); }); + // sendApplicationLog + application.sendApplicationLog(info => { + console.log("Application logId:"); + console.log(info.logId); + }); + // setAppLogUsername + application.setAppLogUsername("username", () => { + console.log("Successfully set app log username"); + }, error => { + console.log("Failed to set app log username. Error: ", error); + }); // setShortcuts application.setShortcuts({ desktop: true, @@ -127,6 +149,12 @@ function test_application() { application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { console.log(`The mouse has clicked at (${clickInfo.x}, ${clickInfo.y})`); }); + // setZoomLevel + application.setZoomLevel(2, () => { + console.log("Successfully set application zoom level"); + }, error => { + console.log("Failed to set application zoom level. Error: ", error); + }); // terminate application.terminate(); // wait From e126c80e8dadc1a0f0f75c5da8ce43741cccdedf Mon Sep 17 00:00:00 2001 From: maksimovicdanijel Date: Sun, 27 Jan 2019 17:29:04 +0100 Subject: [PATCH 180/312] Add types for react-howler package --- types/react-howler/index.d.ts | 49 +++++++++++++++++++++++ types/react-howler/react-howler-tests.tsx | 39 ++++++++++++++++++ types/react-howler/tsconfig.json | 17 ++++++++ types/react-howler/tslint.json | 1 + 4 files changed, 106 insertions(+) create mode 100644 types/react-howler/index.d.ts create mode 100644 types/react-howler/react-howler-tests.tsx create mode 100644 types/react-howler/tsconfig.json create mode 100644 types/react-howler/tslint.json diff --git a/types/react-howler/index.d.ts b/types/react-howler/index.d.ts new file mode 100644 index 0000000000..51722f9079 --- /dev/null +++ b/types/react-howler/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for react-howler 3.7 +// Project: https://github.com/thangngoc89/react-howler +// Definitions by: Danijel Maksimovic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.2 + +/// +/// + +import * as React from 'react'; +import { Howl } from 'howler'; + +declare enum HOWLER_STATE { + UNLOADED = 'unloaded', + LOADING = 'loading', + LOADED = 'loaded' +} + +interface Props { + src: string | string[]; + format?: string[]; + playing?: boolean; + mute?: boolean; + loop?: boolean; + preload?: boolean; + volume?: number; + onEnd?: () => void; + onPause?: () => void; + onPlay?: (id: number) => void; + onVolume?: (id: number) => void; + onStop?: (id: number) => void; + onLoad?: () => void; + onLoadError?: (id: number) => void; + html5?: boolean; +} + +declare class ReactHowler extends React.Component { + stop(id?: number): void; + + duration(id?: number): number; + + seek(time: number): number; + + howlerState(): HOWLER_STATE; + + howler: Howl; +} + +export default ReactHowler; diff --git a/types/react-howler/react-howler-tests.tsx b/types/react-howler/react-howler-tests.tsx new file mode 100644 index 0000000000..e840da7dde --- /dev/null +++ b/types/react-howler/react-howler-tests.tsx @@ -0,0 +1,39 @@ +import * as React from 'react'; +import ReactHowler from 'react-howler'; + +export class ReactHowlerTest extends React.Component { + private readonly player = React.createRef(); + + render() { + const player = this.player.current; + + if (player) { + player.howler.duration(); + } + + return ( +
    + console.log('playing sound with id ', id)} + onLoad={() => console.log('sound loaded')} + onLoadError={id => + console.log('error loading sound with id ', id) + } + onEnd={() => console.log('sound ended')} + onPause={() => console.log('sound paused')} + onStop={id => console.log('sound with id paused', id)} + volume={0.5} + onVolume={id => console.log('volume changed', id)} + loop={true} + html5={true} + format={['mp3']} + preload={false} + ref={this.player} + /> +
    + ); + } +} diff --git a/types/react-howler/tsconfig.json b/types/react-howler/tsconfig.json new file mode 100644 index 0000000000..fe1b001df3 --- /dev/null +++ b/types/react-howler/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "jsx": "react", + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": false + }, + "files": ["index.d.ts", "react-howler-tests.tsx"] +} diff --git a/types/react-howler/tslint.json b/types/react-howler/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-howler/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bbb2666fa4e348e6ed17488b503fd841b383c9ed Mon Sep 17 00:00:00 2001 From: Jeroen Claassens Date: Tue, 29 Jan 2019 23:23:26 +0100 Subject: [PATCH 181/312] Fix export declaration Signed-off-by: Jeroen Claassens --- types/mui-datatables/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mui-datatables/index.d.ts b/types/mui-datatables/index.d.ts index 8a65c257c1..055406cc6f 100644 --- a/types/mui-datatables/index.d.ts +++ b/types/mui-datatables/index.d.ts @@ -168,6 +168,6 @@ export interface MUIDataTableProps { options?: MUIDataTableOptions; } -export const MUIDataTable: React.ComponentType; +declare const MUIDataTable: React.ComponentType; export default MUIDataTable; From ea9401ad865543ea29901d650c295203c0c9c3b8 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Wed, 30 Jan 2019 00:17:32 +0100 Subject: [PATCH 182/312] Added documentation --- types/coinbase/index.d.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 1e94f04295..82fc32a7d3 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -915,12 +915,24 @@ export class Buy implements Resource { */ payout_at?: string; + /** + * Unit price of the base currency. + */ unit_price: UnitPrice; + /** + * Hold period for transfer. + */ hold_business_days: number; + /** + * Is it the first buy for this symbol? + */ is_first_buy: boolean; + /** + * Is there another action required to make the transfer pass? + */ requires_completion_step: boolean; /** @@ -934,13 +946,28 @@ export class Buy implements Resource { } export interface Fee { - amount: string; + /** + * Amount associated to this fee + */ + amount: MoneyHash; + /** + * Fee beneficiary ("bank", "coinbase", ...) + */ type: string; } export interface UnitPrice { + /** + * Amount as floating-point in a string + */ amount: string; + /** + * Currency e.g. "BTC" (see Client#getCurrencies() for available strings) + */ currency: string; + /** + * Type of price + */ scale: number; } From edd2f7162106ec46dd7721cf6224a24197001c8b Mon Sep 17 00:00:00 2001 From: Andrew Potter Date: Tue, 29 Jan 2019 16:28:58 -0700 Subject: [PATCH 183/312] Split options to improve signature recongition --- types/clean-css/clean-css-tests.ts | 29 +++++++++++++++++++++++ types/clean-css/index.d.ts | 38 ++++++++++++++++++++---------- 2 files changed, 55 insertions(+), 12 deletions(-) diff --git a/types/clean-css/clean-css-tests.ts b/types/clean-css/clean-css-tests.ts index 9c856d40a1..6c92a5ae88 100644 --- a/types/clean-css/clean-css-tests.ts +++ b/types/clean-css/clean-css-tests.ts @@ -81,3 +81,32 @@ new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source, inputSourc console.log(error); } ); + +// test object return when passing options as object +let CleanCssOptions: CleanCSS.Options = { returnPromise: true }; +new CleanCSS(CleanCssOptions).minify(source) + .then((minified: CleanCSS.Output): void => { + console.log(minified.styles); + }).catch((error: any): void => { + console.log(error); + } +); + +CleanCssOptions = { returnPromise: false }; +new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => { + console.log(minified.styles); +}); + + +// type conversion +CleanCssOptions = {}; +// in this case, the compiler will think its an OptionsOutput +// so if we want to make it a promise, we will need to cast it specifically its a promise type return +(CleanCssOptions = CleanCssOptions as CleanCSS.OptionsPromise).returnPromise = true; +new CleanCSS(CleanCssOptions).minify(source) + .then((minified: CleanCSS.Output): void => { + console.log(minified.styles); + }).catch((error: any): void => { + console.log(error); + } +); \ No newline at end of file diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index 244c585e53..f806397540 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -9,15 +9,16 @@ import { RequestOptions as HttpsRequestOptions } from "https"; import { RequestOptions as HttpRequestOptions } from "http"; declare namespace CleanCSS { + /** - * Options passed when initializing a new instance of CleanCSS + * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output */ - interface Options { + interface OptionsBase { /** * Controls compatibility mode used; defaults to ie10+ using `'*'`. * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` */ - compatibility?: "*" | "ie9" | "ie8" | "ie7" | CompatibilityOptions; + compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions; /** * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function @@ -28,7 +29,7 @@ declare namespace CleanCSS { * Controls output CSS formatting; defaults to `false`. * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. */ - format?: "beautify" | "keep-breaks" | FormatOptions | false; + format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false; /** * inline option whitelists which @import rules will be processed. Defaults to `'local'` @@ -56,7 +57,7 @@ declare namespace CleanCSS { * Controls optimization level used; defaults to `1`. * Level hash exposes `1`, and `2`. */ - level?: 0 | 1 | 2 | OptimizationsOptions; + level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions; /** * Controls URL rebasing; defaults to `true`; @@ -69,11 +70,6 @@ declare namespace CleanCSS { */ rebaseTo?: string; - /** - * If you prefer clean-css to return a Promise object then you need to explicitely ask for it; defaults to `false` - */ - returnPromise?: boolean; - /** * Controls whether an output source map is built; defaults to `false` */ @@ -650,12 +646,30 @@ declare namespace CleanCSS { minify(sources: Sources, sourceMap?: string): Promise; } + /** + * Options when returning a promise + */ + type OptionsPromise = OptionsBase & { returnPromise: true }; + + /** + * Options when returning an output + */ + type OptionsOutput = OptionsBase & { returnPromise?: false }; + + /** + * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` + * and want to return a promise, you will need to cast to the correct options type so that TypeScript + * knows what the expected return type will be: + * `(options = options as CleanCSS.OptionsPromise).returnPromise = true` + */ + type Options = OptionsPromise | OptionsOutput; + /** * Constructor interface for CleanCSS */ interface Constructor { - new(options: Options & { returnPromise: true }): MinifierPromise; - new(options?: Options): MinifierOutput; + new(options: OptionsPromise): MinifierPromise; + new(options?: OptionsOutput): MinifierOutput; } } From 4a2ad498c36c150c0bf061e3495849d51ec42875 Mon Sep 17 00:00:00 2001 From: Andrew Potter Date: Tue, 29 Jan 2019 16:35:44 -0700 Subject: [PATCH 184/312] Fixed Linting Errors --- types/clean-css/clean-css-tests.ts | 4 ++-- types/clean-css/index.d.ts | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/types/clean-css/clean-css-tests.ts b/types/clean-css/clean-css-tests.ts index 6c92a5ae88..6c01ba1158 100644 --- a/types/clean-css/clean-css-tests.ts +++ b/types/clean-css/clean-css-tests.ts @@ -1,5 +1,6 @@ // Original by Tanguy Krotoff // Updated by Andrew Potter +// TypeScript Version: 2.4 import * as CleanCSS from 'clean-css'; @@ -97,7 +98,6 @@ new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Out console.log(minified.styles); }); - // type conversion CleanCssOptions = {}; // in this case, the compiler will think its an OptionsOutput @@ -109,4 +109,4 @@ new CleanCSS(CleanCssOptions).minify(source) }).catch((error: any): void => { console.log(error); } -); \ No newline at end of file +); diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index f806397540..c474741ec8 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -9,7 +9,6 @@ import { RequestOptions as HttpsRequestOptions } from "https"; import { RequestOptions as HttpRequestOptions } from "http"; declare namespace CleanCSS { - /** * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output */ @@ -18,7 +17,7 @@ declare namespace CleanCSS { * Controls compatibility mode used; defaults to ie10+ using `'*'`. * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` */ - compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions; + compatibility?: "*" | "ie9" | "ie8" | "ie7" | CompatibilityOptions; /** * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function @@ -29,7 +28,7 @@ declare namespace CleanCSS { * Controls output CSS formatting; defaults to `false`. * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. */ - format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false; + format?: "beautify" | "keep-breaks" | FormatOptions | false; /** * inline option whitelists which @import rules will be processed. Defaults to `'local'` @@ -57,7 +56,7 @@ declare namespace CleanCSS { * Controls optimization level used; defaults to `1`. * Level hash exposes `1`, and `2`. */ - level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions; + level?: 0 | 1 | 2 | OptimizationsOptions; /** * Controls URL rebasing; defaults to `true`; From fa2c66bdb4d1ab3c5baf8392b52384b10af89af8 Mon Sep 17 00:00:00 2001 From: Andrew Potter Date: Tue, 29 Jan 2019 16:40:52 -0700 Subject: [PATCH 185/312] removed type-test as it forces ts version --- types/clean-css/clean-css-tests.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/types/clean-css/clean-css-tests.ts b/types/clean-css/clean-css-tests.ts index 6c01ba1158..98049b3ef6 100644 --- a/types/clean-css/clean-css-tests.ts +++ b/types/clean-css/clean-css-tests.ts @@ -1,6 +1,5 @@ // Original by Tanguy Krotoff // Updated by Andrew Potter -// TypeScript Version: 2.4 import * as CleanCSS from 'clean-css'; @@ -97,16 +96,3 @@ CleanCssOptions = { returnPromise: false }; new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => { console.log(minified.styles); }); - -// type conversion -CleanCssOptions = {}; -// in this case, the compiler will think its an OptionsOutput -// so if we want to make it a promise, we will need to cast it specifically its a promise type return -(CleanCssOptions = CleanCssOptions as CleanCSS.OptionsPromise).returnPromise = true; -new CleanCSS(CleanCssOptions).minify(source) - .then((minified: CleanCSS.Output): void => { - console.log(minified.styles); - }).catch((error: any): void => { - console.log(error); - } -); From bc8c6cabd0ce252a9f5e45011666ff3984b94e76 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Tue, 29 Jan 2019 16:04:09 -0800 Subject: [PATCH 186/312] Add beta tags to EnhancedLocation methods --- types/office-js-preview/index.d.ts | 32 ++++++++++++++++++++++++++---- types/office-js/index.d.ts | 32 ++++++++++++++++++++++++++---- 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index e26ab7e8a0..56415c63cd 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -9411,10 +9411,12 @@ declare namespace Office { * * @beta */ - interface EnhancedLocation { + export interface EnhancedLocation { /** * Adds to the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks * * @@ -9436,11 +9438,15 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ addAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** * Adds to the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9456,11 +9462,15 @@ declare namespace Office { * @param locationIdentifiers The locations to be added to the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; /** * Gets the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9481,11 +9491,15 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. + * + * @beta */ getAsync(options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; /** * Gets the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9500,6 +9514,8 @@ declare namespace Office { * * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. + * + * @beta */ getAsync(callback?: (result: Office.AsyncResult) => void): void; /** @@ -9507,6 +9523,8 @@ declare namespace Office { * * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9528,6 +9546,8 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ removeAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** @@ -9535,6 +9555,8 @@ declare namespace Office { * * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9550,6 +9572,8 @@ declare namespace Office { * @param locationIdentifiers The locations to be removed from the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; } @@ -9964,7 +9988,7 @@ declare namespace Office { */ end: Time; /** - * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link EnhancedLocation} object that + * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link Office.EnhancedLocation} object that * provides methods to get, remove, or add locations on an item. * * [Api set: Mailbox Preview] @@ -11075,8 +11099,8 @@ declare namespace Office { /** * Gets the locations of an appointment. * - * The enhancedLocation property returns an {@link EnhancedLocation} object that allows you to get the set of locations (each represented by - * a {@link LocationDetails} object) associated with the appointment. + * The enhancedLocation property returns an {@link Office.EnhancedLocation} object that allows you to get the set of locations (each represented by + * a {@link Office.LocationDetails} object) associated with the appointment. * * [Api set: Mailbox Preview] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 1b3f3c447a..1ff4d05df3 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -9411,10 +9411,12 @@ declare namespace Office { * * @beta */ - interface EnhancedLocation { + export interface EnhancedLocation { /** * Adds to the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9436,11 +9438,15 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ addAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** * Adds to the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9456,11 +9462,15 @@ declare namespace Office { * @param locationIdentifiers The locations to be added to the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ addAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; /** * Gets the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9481,11 +9491,15 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. + * + * @beta */ getAsync(options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; /** * Gets the set of locations associated with the appointment. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9500,6 +9514,8 @@ declare namespace Office { * * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. + * + * @beta */ getAsync(callback?: (result: Office.AsyncResult) => void): void; /** @@ -9507,6 +9523,8 @@ declare namespace Office { * * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9528,6 +9546,8 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ removeAsync(locationIdentifiers: LocationIdentifier[], options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResultStatus) => void): void; /** @@ -9535,6 +9555,8 @@ declare namespace Office { * * If there are multiple locations with the same name, all matching locations will be removed even if only one was specified in locationIdentifiers. * + * [Api set: Mailbox Preview] + * * @remarks *
    * @@ -9550,6 +9572,8 @@ declare namespace Office { * @param locationIdentifiers The locations to be removed from the current list of locations. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. Check the `status` property of asyncResult to determine if the call succeeded. + * + * @beta */ removeAsync(locationIdentifiers: LocationIdentifier[], callback?: (result: Office.AsyncResultStatus) => void): void; } @@ -9964,7 +9988,7 @@ declare namespace Office { */ end: Time; /** - * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link EnhancedLocation} object that + * Gets or sets the locations of the appointment. The `enhancedLocation` property returns an {@link Office.EnhancedLocation} object that * provides methods to get, remove, or add locations on an item. * * [Api set: Mailbox Preview] @@ -11075,8 +11099,8 @@ declare namespace Office { /** * Gets the locations of an appointment. * - * The enhancedLocation property returns an {@link EnhancedLocation} object that allows you to get the set of locations (each represented by - * a {@link LocationDetails} object) associated with the appointment. + * The enhancedLocation property returns an {@link Office.EnhancedLocation} object that allows you to get the set of locations (each represented by + * a {@link Office.LocationDetails} object) associated with the appointment. * * [Api set: Mailbox Preview] * From 0b3f86bacbaffdbd015c303c42068289a41dba47 Mon Sep 17 00:00:00 2001 From: Janeene Beeforth Date: Wed, 30 Jan 2019 12:23:46 +1100 Subject: [PATCH 187/312] Abstract getters on Luzon Zone are not static. With the current definition, several items that are supposed to be public members/methods are marked static. Since these are supposed to be returning information for a particular zone, and in the luxon source they are not static members/methods, they should not be marked as static. It is not possible to create an implementation for Zone using the current definition. References: https://moment.github.io/luxon/docs/class/src/zone.js~Zone.html https://github.com/moment/luxon/blob/master/src/zone.js --- types/luxon/index.d.ts | 11 ++++++----- types/luxon/luxon-tests.ts | 20 +++++++++++++++++++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 890d0731ad..b5f1134fb5 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -5,6 +5,7 @@ // Jonathan Siebern // Matt R. Wilson // Pietro Vismara +// Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -467,11 +468,11 @@ export interface ZoneOffsetOptions { } export class Zone { - static offsetName(ts: number, options?: ZoneOffsetOptions): string; - static isValid: boolean; - static name: string; - static type: string; - static universal: boolean; + offsetName(ts: number, options?: ZoneOffsetOptions): string; + isValid: boolean; + name: string; + type: string; + universal: boolean; equals(other: Zone): boolean; offset(ts: number): number; } diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index 3cadfa5779..df5481094b 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -1,4 +1,4 @@ -import { DateTime, Duration, Interval, Info, Settings, IANAZone } from 'luxon'; +import { DateTime, Duration, Interval, Info, Settings, IANAZone, Zone, ZoneOffsetOptions } from 'luxon'; /* DateTime */ const dt = DateTime.local(2017, 5, 15, 8, 30); @@ -285,3 +285,21 @@ dur.reconfigure({ conversionAccuracy: 'longterm' }); // $ExpectType Duration start.until(end); // $ExpectType Interval i.toDuration(['years', 'months', 'days']); // $ExpectType Duration + +/* Sample Zone Implementation */ +class SampleZone extends Zone { + readonly isValid = false; + readonly name = 'Sample'; + readonly type = 'Example'; + readonly universal = true; + + offsetName(ts: number, options?: ZoneOffsetOptions) { + return 'SampleZone'; + } + equals(other: Zone) { + return other.name === this.name; + } + offset(ts: number) { + return 0; + } +} From 8456cf18125d36c7110eedf68a9b6d29505152b2 Mon Sep 17 00:00:00 2001 From: Matt Krick Date: Tue, 29 Jan 2019 17:50:45 -0800 Subject: [PATCH 188/312] fix loadMore call sig, make pageInfo nullable --- types/react-relay/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index acce5bf832..d830d22b18 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -6,6 +6,7 @@ // Nicolas Pirotte // Cameron Knight // Kaare Hoff Skovgaard +// Matt Krick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -130,15 +131,14 @@ export interface PageInfo { } export interface ConnectionData { edges?: ReadonlyArray; - pageInfo?: Partial; + pageInfo?: Partial | null; } export type RelayPaginationProp = RelayProp & { hasMore(): boolean; isLoading(): boolean; loadMore( pageSize: number, - callback: (error?: Error) => void, - options?: RefetchOptions + callback?: (error?: Error) => void ): RelayRuntimeTypes.Disposable | undefined | null; refetchConnection( totalCount: number, From 2b0639b6307d79d61083b1ec602cc59aaff2a785 Mon Sep 17 00:00:00 2001 From: Ilya Zaytsev Date: Mon, 28 Jan 2019 08:20:37 +0700 Subject: [PATCH 189/312] [set-cookie-parser] add options definition --- types/set-cookie-parser/index.d.ts | 10 ++++++++-- .../set-cookie-parser-tests.ts | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/types/set-cookie-parser/index.d.ts b/types/set-cookie-parser/index.d.ts index ea00ab4399..3da321ddb0 100644 --- a/types/set-cookie-parser/index.d.ts +++ b/types/set-cookie-parser/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for set-cookie-parser // Project: https://github.com/nfriedly/set-cookie-parser // Definitions by: Nick Paddock +// Ilya Zaytsev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,10 +9,10 @@ declare module "set-cookie-parser" { import http = require("http"); - function SetCookieParser(input: string | ReadonlyArray | http.IncomingMessage): SetCookieParser.Cookie[]; + function SetCookieParser(input: string | ReadonlyArray | http.IncomingMessage, options?: SetCookieParser.Options): SetCookieParser.Cookie[]; namespace SetCookieParser { - function parse(input: string | ReadonlyArray | http.IncomingMessage): Cookie[]; + function parse(input: string | ReadonlyArray | http.IncomingMessage, options?: Options): Cookie[]; function splitCookiesString(input: string | ReadonlyArray | void): string[]; @@ -25,6 +26,11 @@ declare module "set-cookie-parser" { secure?: boolean; httpOnly?: boolean; } + + type Options = { + decodeValues?: boolean; + map?: boolean; + } } export = SetCookieParser; diff --git a/types/set-cookie-parser/set-cookie-parser-tests.ts b/types/set-cookie-parser/set-cookie-parser-tests.ts index ab4e88005d..578e257f0c 100644 --- a/types/set-cookie-parser/set-cookie-parser-tests.ts +++ b/types/set-cookie-parser/set-cookie-parser-tests.ts @@ -88,3 +88,22 @@ assert.deepStrictEqual(cookiesString, [ 'foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure', 'baz=buz; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure', ]) + +// Use decodeValues=false option +var notDecodedValueCookies = setCookie.parse('user=%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 3000 10:01:11 GMT; HttpOnly; Secure', { decodeValues: false }); +assert.equal(notDecodedValueCookies[0].value, '%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2'); + +var decodedValueCookies = setCookie.parse('user=%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 3000 10:01:11 GMT; HttpOnly; Secure', { decodeValues: true }); +assert.equal(decodedValueCookies[0].value, 'Илья Зайцев'); + +// Use map=true option +var expectedCookiesMap = { + foo: { + name: 'foo', + value: 'bar', + maxAge: 1000, + domain: '.example.com', + } +}; +var cookiesMap = setCookie.parse('foo=bar; Max-Age=1000; Domain=.example.com;', { map: true }); +assert.deepStrictEqual(cookiesMap, expectedCookiesMap); \ No newline at end of file From fd1e25151a335a8e942f870038ae1e58b41a60cc Mon Sep 17 00:00:00 2001 From: MuTsunTsai <39870664+MuTsunTsai@users.noreply.github.com> Date: Wed, 30 Jan 2019 10:27:33 +0800 Subject: [PATCH 190/312] Add Size.set methods --- types/paper/index.d.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 08a6d794ad..409366488f 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1109,6 +1109,37 @@ declare module paper { modulo(size: number[]): Size; modulo(size: number): Size; + /** + * Sets the size with the given width and height values. + * @param width - the width + * @param height - the height + */ + set(width: number, height: number): Size; + + /** + * Sets the size using the numbers in the given array as dimensions. + * @param array - an array of numbers + */ + set(array: number[]): Size; + + /** + * Sets the size using the properties in the given object. + * @param object - the object literal containing properies (width:10, height:10 etc) + */ + set(object: any): Size; + + /** + * Sets the size using the coordinates of the given Size object. + * @param size - the size to duplicate from + */ + set(size: Size): Size; + + /** + * Sets the size using the point.x and point.y values of the given Point object. + * @param point - the point from which to create a size + */ + set(point: Point): Size; + } export interface IFrameEvent { From 6aa2877dbcd97b84ee3bbdd25b73f7d56e840d7d Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 11:45:52 +0530 Subject: [PATCH 191/312] Incorporating review --- types/happypack/index.d.ts | 13 +++---- types/happypack/tslint.json | 78 +------------------------------------ 2 files changed, 7 insertions(+), 84 deletions(-) diff --git a/types/happypack/index.d.ts b/types/happypack/index.d.ts index e1f6a8947e..d865761784 100644 --- a/types/happypack/index.d.ts +++ b/types/happypack/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for happypack +// Type definitions for happypack 5.0 // Project: https://github.com/amireh/happypack // Definitions by: Akash Vishwakarma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,17 +6,16 @@ import { Plugin } from 'webpack'; -declare class HappyPack extends Plugin { - - constructor(options?: HappyPack.PluginOptions); -} +export = HappyPack; declare namespace HappyPack { interface PluginOptions { id?: string; threads?: number; - loaders?: any; + loaders: any; } } -export = HappyPack; +declare class HappyPack extends Plugin { + constructor(options: HappyPack.PluginOptions); +} diff --git a/types/happypack/tslint.json b/types/happypack/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/happypack/tslint.json +++ b/types/happypack/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From 1f85e5c368f2a09ede8bd6346f960573aa230471 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:09:07 +0530 Subject: [PATCH 192/312] Renaming folder name as it is same as module name i am unable to import in test --- types/happy-pack/happypack-tests.ts | 5 +++++ types/{happypack => happy-pack}/index.d.ts | 9 +++++---- types/{happypack => happy-pack}/tsconfig.json | 8 ++++---- types/{happypack => happy-pack}/tslint.json | 0 4 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 types/happy-pack/happypack-tests.ts rename types/{happypack => happy-pack}/index.d.ts (73%) rename types/{happypack => happy-pack}/tsconfig.json (78%) rename types/{happypack => happy-pack}/tslint.json (100%) diff --git a/types/happy-pack/happypack-tests.ts b/types/happy-pack/happypack-tests.ts new file mode 100644 index 0000000000..7f2c24daf5 --- /dev/null +++ b/types/happy-pack/happypack-tests.ts @@ -0,0 +1,5 @@ +import * as happyPack from 'happy-pack'; + +const ref: happyPack = new happyPack({ + loaders: ['ts-loader'] +}); diff --git a/types/happypack/index.d.ts b/types/happy-pack/index.d.ts similarity index 73% rename from types/happypack/index.d.ts rename to types/happy-pack/index.d.ts index d865761784..e6f30343da 100644 --- a/types/happypack/index.d.ts +++ b/types/happy-pack/index.d.ts @@ -6,9 +6,9 @@ import { Plugin } from 'webpack'; -export = HappyPack; +export = happypack; -declare namespace HappyPack { +declare namespace happypack { interface PluginOptions { id?: string; threads?: number; @@ -16,6 +16,7 @@ declare namespace HappyPack { } } -declare class HappyPack extends Plugin { - constructor(options: HappyPack.PluginOptions); +declare class happypack extends Plugin { + constructor(options: happypack.PluginOptions); } + diff --git a/types/happypack/tsconfig.json b/types/happy-pack/tsconfig.json similarity index 78% rename from types/happypack/tsconfig.json rename to types/happy-pack/tsconfig.json index 82e6284376..bfd5e35551 100644 --- a/types/happypack/tsconfig.json +++ b/types/happy-pack/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "happypack-tests.ts" ] } \ No newline at end of file diff --git a/types/happypack/tslint.json b/types/happy-pack/tslint.json similarity index 100% rename from types/happypack/tslint.json rename to types/happy-pack/tslint.json From ce936f03f7725c18a90557a13858acb7bc9f9516 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:10:13 +0530 Subject: [PATCH 193/312] Update happy-pack-tests.ts --- types/happy-pack/{happypack-tests.ts => happy-pack-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename types/happy-pack/{happypack-tests.ts => happy-pack-tests.ts} (100%) diff --git a/types/happy-pack/happypack-tests.ts b/types/happy-pack/happy-pack-tests.ts similarity index 100% rename from types/happy-pack/happypack-tests.ts rename to types/happy-pack/happy-pack-tests.ts From 4260f90627775dd8a1e7d49a01234a1d932678cf Mon Sep 17 00:00:00 2001 From: Jack Willis-Craig Date: Wed, 30 Jan 2019 17:47:27 +1000 Subject: [PATCH 194/312] fix(react-native): add missing flashScrollIndicators method to FlatList component --- types/react-native/index.d.ts | 5 +++++ types/react-native/test/index.tsx | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2b59454222..4b06119df2 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -4111,6 +4111,11 @@ export class FlatList extends React.Component> { * by taps on items or by navigation actions. */ recordInteraction: () => void; + + /** + * Displays the scroll indicators momentarily. + */ + flashScrollIndicators: () => void; } /** diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 1fcbe153e6..801565dc8d 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -332,6 +332,14 @@ InteractionManager.runAfterInteractions(() => { }).then(() => "done"); export class FlatListTest extends React.Component, {}> { + list: FlatList | null = null; + + componentDidMount(): void { + if (this.list) { + this.list.flashScrollIndicators(); + } + } + _renderItem = (rowData: any) => { return ( @@ -345,6 +353,7 @@ export class FlatListTest extends React.Component, {}> { render() { return ( (this.list = list)} data={[1, 2, 3, 4, 5]} renderItem={this._renderItem} ItemSeparatorComponent={this._renderSeparator} From 8ae9055d647d6f0f3601fbcb1a75b3b7327d771f Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:24:26 +0530 Subject: [PATCH 195/312] renaming folder unable tp import in test --- types/happy-pack/happy-pack-tests.ts | 5 ----- types/happy-packs/happy-pack-tests.ts | 5 +++++ types/{happy-pack => happy-packs}/index.d.ts | 3 +-- types/{happy-pack => happy-packs}/tsconfig.json | 2 +- types/{happy-pack => happy-packs}/tslint.json | 0 5 files changed, 7 insertions(+), 8 deletions(-) delete mode 100644 types/happy-pack/happy-pack-tests.ts create mode 100644 types/happy-packs/happy-pack-tests.ts rename types/{happy-pack => happy-packs}/index.d.ts (99%) rename types/{happy-pack => happy-packs}/tsconfig.json (93%) rename types/{happy-pack => happy-packs}/tslint.json (100%) diff --git a/types/happy-pack/happy-pack-tests.ts b/types/happy-pack/happy-pack-tests.ts deleted file mode 100644 index 7f2c24daf5..0000000000 --- a/types/happy-pack/happy-pack-tests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as happyPack from 'happy-pack'; - -const ref: happyPack = new happyPack({ - loaders: ['ts-loader'] -}); diff --git a/types/happy-packs/happy-pack-tests.ts b/types/happy-packs/happy-pack-tests.ts new file mode 100644 index 0000000000..928221b893 --- /dev/null +++ b/types/happy-packs/happy-pack-tests.ts @@ -0,0 +1,5 @@ +import * as happyPacks from 'happy-packs'; + +const ref: happyPacks = new happyPacks({ + loaders: ['ts-loader'] +}); diff --git a/types/happy-pack/index.d.ts b/types/happy-packs/index.d.ts similarity index 99% rename from types/happy-pack/index.d.ts rename to types/happy-packs/index.d.ts index e6f30343da..3df45fdfe9 100644 --- a/types/happy-pack/index.d.ts +++ b/types/happy-packs/index.d.ts @@ -18,5 +18,4 @@ declare namespace happypack { declare class happypack extends Plugin { constructor(options: happypack.PluginOptions); -} - +} \ No newline at end of file diff --git a/types/happy-pack/tsconfig.json b/types/happy-packs/tsconfig.json similarity index 93% rename from types/happy-pack/tsconfig.json rename to types/happy-packs/tsconfig.json index bfd5e35551..d6ff7c28fc 100644 --- a/types/happy-pack/tsconfig.json +++ b/types/happy-packs/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "happypack-tests.ts" + "happy-packs-tests.ts" ] } \ No newline at end of file diff --git a/types/happy-pack/tslint.json b/types/happy-packs/tslint.json similarity index 100% rename from types/happy-pack/tslint.json rename to types/happy-packs/tslint.json From 24bda892237c73900b28aa92e65f966f54bf0d6f Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:26:33 +0530 Subject: [PATCH 196/312] renaming back --- .../happy-pack-tests.ts => happy-pack/happy-packs-tests.ts} | 2 +- types/{happy-packs => happy-pack}/index.d.ts | 0 types/{happy-packs => happy-pack}/tsconfig.json | 2 +- types/{happy-packs => happy-pack}/tslint.json | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename types/{happy-packs/happy-pack-tests.ts => happy-pack/happy-packs-tests.ts} (61%) rename types/{happy-packs => happy-pack}/index.d.ts (100%) rename types/{happy-packs => happy-pack}/tsconfig.json (93%) rename types/{happy-packs => happy-pack}/tslint.json (100%) diff --git a/types/happy-packs/happy-pack-tests.ts b/types/happy-pack/happy-packs-tests.ts similarity index 61% rename from types/happy-packs/happy-pack-tests.ts rename to types/happy-pack/happy-packs-tests.ts index 928221b893..0a879c7f2e 100644 --- a/types/happy-packs/happy-pack-tests.ts +++ b/types/happy-pack/happy-packs-tests.ts @@ -1,4 +1,4 @@ -import * as happyPacks from 'happy-packs'; +import * as happyPacks from 'happy-pack'; const ref: happyPacks = new happyPacks({ loaders: ['ts-loader'] diff --git a/types/happy-packs/index.d.ts b/types/happy-pack/index.d.ts similarity index 100% rename from types/happy-packs/index.d.ts rename to types/happy-pack/index.d.ts diff --git a/types/happy-packs/tsconfig.json b/types/happy-pack/tsconfig.json similarity index 93% rename from types/happy-packs/tsconfig.json rename to types/happy-pack/tsconfig.json index d6ff7c28fc..4e7f0f6660 100644 --- a/types/happy-packs/tsconfig.json +++ b/types/happy-pack/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "happy-packs-tests.ts" + "happy-pack-tests.ts" ] } \ No newline at end of file diff --git a/types/happy-packs/tslint.json b/types/happy-pack/tslint.json similarity index 100% rename from types/happy-packs/tslint.json rename to types/happy-pack/tslint.json From f78899b07047dae4a0eaa04011533d0ad9b3c10f Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:38:14 +0530 Subject: [PATCH 197/312] updating code hope this time test will run without errror --- types/happy-pack/happy-pack-tests.ts | 5 +++++ types/happy-pack/happy-packs-tests.ts | 5 ----- 2 files changed, 5 insertions(+), 5 deletions(-) create mode 100644 types/happy-pack/happy-pack-tests.ts delete mode 100644 types/happy-pack/happy-packs-tests.ts diff --git a/types/happy-pack/happy-pack-tests.ts b/types/happy-pack/happy-pack-tests.ts new file mode 100644 index 0000000000..7f2c24daf5 --- /dev/null +++ b/types/happy-pack/happy-pack-tests.ts @@ -0,0 +1,5 @@ +import * as happyPack from 'happy-pack'; + +const ref: happyPack = new happyPack({ + loaders: ['ts-loader'] +}); diff --git a/types/happy-pack/happy-packs-tests.ts b/types/happy-pack/happy-packs-tests.ts deleted file mode 100644 index 0a879c7f2e..0000000000 --- a/types/happy-pack/happy-packs-tests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as happyPacks from 'happy-pack'; - -const ref: happyPacks = new happyPacks({ - loaders: ['ts-loader'] -}); From 82008c3d3a620155672186430b83ee4d864799e7 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:41:57 +0530 Subject: [PATCH 198/312] Fixing new line err --- types/happy-pack/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/happy-pack/index.d.ts b/types/happy-pack/index.d.ts index 3df45fdfe9..13c212a3f8 100644 --- a/types/happy-pack/index.d.ts +++ b/types/happy-pack/index.d.ts @@ -18,4 +18,4 @@ declare namespace happypack { declare class happypack extends Plugin { constructor(options: happypack.PluginOptions); -} \ No newline at end of file +} From d8784261371a42d939d1666ba4f950903ca1dc28 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 13:49:37 +0530 Subject: [PATCH 199/312] Update happy-pack-tests.ts --- types/happy-pack/happy-pack-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/happy-pack/happy-pack-tests.ts b/types/happy-pack/happy-pack-tests.ts index 7f2c24daf5..b003489431 100644 --- a/types/happy-pack/happy-pack-tests.ts +++ b/types/happy-pack/happy-pack-tests.ts @@ -1,5 +1,7 @@ import * as happyPack from 'happy-pack'; const ref: happyPack = new happyPack({ + id: '1', + threads: 1, loaders: ['ts-loader'] }); From 6439a7378211547a95f0844813ad2d7cddeaf773 Mon Sep 17 00:00:00 2001 From: Simon Kostede Date: Wed, 30 Jan 2019 10:23:50 +0100 Subject: [PATCH 200/312] fix typo in types/google__maps definition of QueryAutocompleteResult --- types/google__maps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts index d393286dfe..f1df5d8f38 100644 --- a/types/google__maps/index.d.ts +++ b/types/google__maps/index.d.ts @@ -3107,7 +3107,7 @@ export interface QueryAutocompleteResult { * contains an `offset` value and a `length`. * These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired. */ - matched_substring: PredictionSubstring[]; + matched_substrings: PredictionSubstring[]; } /** A Radar Search request must include at least one of `keyword`, `name`, or `type`. */ From 3cb4d74e30c6ac565ac500c8252c1b4c110690b3 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 01:59:00 -0800 Subject: [PATCH 201/312] node-forge: a Byte is a number, not a string Signed-off-by: Anders Kaseorg --- types/node-forge/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 1d9b0cb858..6e7d5d136e 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -15,7 +15,7 @@ /// declare module "node-forge" { - type Byte = string; + type Byte = number; type Bytes = string; type Hex = string; type Base64 = string; From 91f106ba56f5d3f309281285e9855bc983fb2b2c Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 02:06:14 -0800 Subject: [PATCH 202/312] node-forge: Asn1.value may be Bytes Signed-off-by: Anders Kaseorg --- types/node-forge/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 6e7d5d136e..67e12c35bd 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -359,10 +359,10 @@ declare module "node-forge" { type: Type; constructed: boolean; composed: boolean; - value: Asn1[]; + value: Bytes | Asn1[]; } - function create(tagClass: Class, type: Type, constructed: boolean, value: string | Asn1[]): Asn1; + function create(tagClass: Class, type: Type, constructed: boolean, value: Bytes | Asn1[]): Asn1; function fromDer(bytes: Bytes | util.ByteBuffer, strict?: boolean): Asn1; function toDer(obj: Asn1): util.ByteBuffer; function oidToDer(oid: OID): util.ByteStringBuffer; From d90e56c86fc7e84b96cf84a5fc56b84f04ffb721 Mon Sep 17 00:00:00 2001 From: Vinay Bedre Date: Wed, 30 Jan 2019 11:10:14 +0100 Subject: [PATCH 203/312] expose isRedirect method of node-fetch in types --- types/node-fetch/index.d.ts | 9 ++++++++- types/node-fetch/node-fetch-tests.ts | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/types/node-fetch/index.d.ts b/types/node-fetch/index.d.ts index 4b12734363..1177e8da25 100644 --- a/types/node-fetch/index.d.ts +++ b/types/node-fetch/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bitinn/node-fetch // Definitions by: Torsten Werner // Niklas Lindgren +// Vinay Bedre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -168,7 +169,13 @@ export type HeaderInit = Headers | string[]; export type BodyInit = ArrayBuffer | ArrayBufferView | NodeJS.ReadableStream | string | URLSearchParams; export type RequestInfo = string | Request; -export default function fetch( +declare function fetch( url: string | Request, init?: RequestInit ): Promise; + +declare namespace fetch { + function isRedirect(code: number): boolean; +} + +export default fetch; diff --git a/types/node-fetch/node-fetch-tests.ts b/types/node-fetch/node-fetch-tests.ts index 7561ae1b0f..f5e940d5d2 100644 --- a/types/node-fetch/node-fetch-tests.ts +++ b/types/node-fetch/node-fetch-tests.ts @@ -77,3 +77,8 @@ function test_headersRaw() { const myHeader = 'foo'; headers.raw()[myHeader]; // $ExpectType string[] } + +function test_isRedirect() { + fetch.isRedirect(301); + fetch.isRedirect(201); +} From dcaee48cf26193516c92d503eceba6c9c73bad21 Mon Sep 17 00:00:00 2001 From: Vinay Date: Wed, 30 Jan 2019 11:16:33 +0100 Subject: [PATCH 204/312] corrected indentation --- types/node-fetch/node-fetch-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/node-fetch/node-fetch-tests.ts b/types/node-fetch/node-fetch-tests.ts index f5e940d5d2..d35114f60a 100644 --- a/types/node-fetch/node-fetch-tests.ts +++ b/types/node-fetch/node-fetch-tests.ts @@ -79,6 +79,6 @@ function test_headersRaw() { } function test_isRedirect() { - fetch.isRedirect(301); - fetch.isRedirect(201); + fetch.isRedirect(301); + fetch.isRedirect(201); } From 017754a9b96beb665166693e138674cbcf488c84 Mon Sep 17 00:00:00 2001 From: Akash Vishwakarma Date: Wed, 30 Jan 2019 17:38:22 +0530 Subject: [PATCH 205/312] It will not work if i take happy-pack so changing to happypack --- .../happy-pack-tests.ts => happypack/happypack-tests.ts} | 2 +- types/{happy-pack => happypack}/index.d.ts | 0 types/{happy-pack => happypack}/tsconfig.json | 2 +- types/{happy-pack => happypack}/tslint.json | 0 4 files changed, 2 insertions(+), 2 deletions(-) rename types/{happy-pack/happy-pack-tests.ts => happypack/happypack-tests.ts} (69%) rename types/{happy-pack => happypack}/index.d.ts (100%) rename types/{happy-pack => happypack}/tsconfig.json (93%) rename types/{happy-pack => happypack}/tslint.json (100%) diff --git a/types/happy-pack/happy-pack-tests.ts b/types/happypack/happypack-tests.ts similarity index 69% rename from types/happy-pack/happy-pack-tests.ts rename to types/happypack/happypack-tests.ts index b003489431..c0ab2d77cf 100644 --- a/types/happy-pack/happy-pack-tests.ts +++ b/types/happypack/happypack-tests.ts @@ -1,4 +1,4 @@ -import * as happyPack from 'happy-pack'; +import * as happyPack from 'happypack'; const ref: happyPack = new happyPack({ id: '1', diff --git a/types/happy-pack/index.d.ts b/types/happypack/index.d.ts similarity index 100% rename from types/happy-pack/index.d.ts rename to types/happypack/index.d.ts diff --git a/types/happy-pack/tsconfig.json b/types/happypack/tsconfig.json similarity index 93% rename from types/happy-pack/tsconfig.json rename to types/happypack/tsconfig.json index 4e7f0f6660..bfd5e35551 100644 --- a/types/happy-pack/tsconfig.json +++ b/types/happypack/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "happy-pack-tests.ts" + "happypack-tests.ts" ] } \ No newline at end of file diff --git a/types/happy-pack/tslint.json b/types/happypack/tslint.json similarity index 100% rename from types/happy-pack/tslint.json rename to types/happypack/tslint.json From 0f67387efb781ab1513067389a6283772b7e1d13 Mon Sep 17 00:00:00 2001 From: Florian Keller Date: Wed, 30 Jan 2019 15:14:10 +0100 Subject: [PATCH 206/312] Add types for npm-license-crawler --- types/npm-license-crawler/index.d.ts | 43 +++++++++++++++++++ .../npm-license-crawler-tests.ts | 15 +++++++ types/npm-license-crawler/tsconfig.json | 23 ++++++++++ types/npm-license-crawler/tslint.json | 1 + 4 files changed, 82 insertions(+) create mode 100644 types/npm-license-crawler/index.d.ts create mode 100644 types/npm-license-crawler/npm-license-crawler-tests.ts create mode 100644 types/npm-license-crawler/tsconfig.json create mode 100644 types/npm-license-crawler/tslint.json diff --git a/types/npm-license-crawler/index.d.ts b/types/npm-license-crawler/index.d.ts new file mode 100644 index 0000000000..82c486b795 --- /dev/null +++ b/types/npm-license-crawler/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for npm-license-crawler 0.1 +// Project: https://github.com/mwittig/npm-license-crawler +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export interface Licenses { + [repository: string]: { + licenses: string; + licenseUrl: string; + parents: string; + repository: string; + }; +} + +export interface CrawlerOptions { + /** export the data as comma-separated values to the given file. The path will be created if it does not exist. */ + csv?: string; + /** show only third-party licenses, i.e., only list the dependencies defined in package.json. */ + dependencies?: boolean; + /** show only development dependencies */ + development?: boolean; + /** path to a directory to be excluded (and its subdirectories) from the search. */ + exclude?: string | string[]; + /** export data as JSON to the given file. The path will be created if it does not exist. */ + json?: string; + /** omit version numbers in result (e.g. "npm-license-crawler@0.1.5" becomes "npm-license-crawler") */ + omitVersion?: boolean; + /** show only direct dependencies licenses, i.e., don't list dependencies of dependencies. */ + onlyDirectDependencies?: boolean; + /** show only production dependencies */ + production?: boolean; + /** output the relative file path for license files. */ + relativeLicensePath?: boolean; + /** path to the directory the license search should start from. If omitted the current working directory is assumed. */ + start: string | string[]; + /** show only licenses that can't be determined or have been guessed. */ + unknown?: boolean; +} + +export type Callback = (error: Error | null, licenses: Licenses) => void; + +export function dumpLicenses(args: CrawlerOptions, callback: Callback): void; diff --git a/types/npm-license-crawler/npm-license-crawler-tests.ts b/types/npm-license-crawler/npm-license-crawler-tests.ts new file mode 100644 index 0000000000..dae39fec09 --- /dev/null +++ b/types/npm-license-crawler/npm-license-crawler-tests.ts @@ -0,0 +1,15 @@ +import { CrawlerOptions, dumpLicenses } from 'npm-license-crawler'; + +const options: CrawlerOptions = { + start: ['../..'], + exclude: ['.'], + json: 'licenses.json', + unknown: true, +}; + +dumpLicenses(options, (error, res) => { + res.name.licenses; // $ExpectType string + res.name.licenseUrl; // $ExpectType string + res.name.parents; // $ExpectType string + res.name.repository; // $ExpectType string +}); diff --git a/types/npm-license-crawler/tsconfig.json b/types/npm-license-crawler/tsconfig.json new file mode 100644 index 0000000000..59df3a8697 --- /dev/null +++ b/types/npm-license-crawler/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", + "npm-license-crawler-tests.ts" + ] +} diff --git a/types/npm-license-crawler/tslint.json b/types/npm-license-crawler/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-license-crawler/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c33e3eddfceea9c699c153e0b71c12aab78a1743 Mon Sep 17 00:00:00 2001 From: Matt Krick Date: Wed, 30 Jan 2019 07:50:33 -0800 Subject: [PATCH 207/312] fix loadMore call sig, make pageInfo nullable --- types/react-relay/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 24e86379bf..2d5146289f 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -139,7 +139,8 @@ export type RelayPaginationProp = RelayProp & { isLoading(): boolean; loadMore( pageSize: number, - callback?: (error?: Error) => void + callback?: ((error?: Error) => void) | null, + options?: RefetchOptions ): RelayRuntimeTypes.Disposable | undefined | null; refetchConnection( totalCount: number, From 3dcf34784e1636a30f39f39679b8d942e638e679 Mon Sep 17 00:00:00 2001 From: Andrei Mihailov Date: Wed, 30 Jan 2019 17:39:58 +0100 Subject: [PATCH 208/312] Fix projection related types --- types/react-simple-maps/index.d.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/types/react-simple-maps/index.d.ts b/types/react-simple-maps/index.d.ts index e76c4e3f0d..4c63f28c69 100644 --- a/types/react-simple-maps/index.d.ts +++ b/types/react-simple-maps/index.d.ts @@ -1,10 +1,12 @@ // Type definitions for react-simple-maps 0.12 // Project: https://github.com/zcreativelabs/react-simple-maps#readme // Definitions by: Novikov Mihail +// Andrej Mihajlov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; +import { GeoProjection } from 'd3-geo'; export type Point = [number, number]; @@ -19,17 +21,21 @@ export interface Line { }; } +export type ProjectionConfig = { + scale: number; + xOffset: number; + yOffset: number; + rotation: [number, number, number]; + precision: number; +}; + +export type ProjectionFunction = (width: number, height: number, config: ProjectionConfig) => GeoProjection; + export interface ComposableMapProps { width?: number; height?: number; - projection?: string | (() => void); - projectionConfig?: { - scale?: number; - xOffset?: number; - yOffset?: number; - rotation?: number[]; - precision?: number; - }; + projection?: string | ProjectionFunction; + projectionConfig?: Partial; style?: React.CSSProperties; defs?: SVGDefsElement; className?: string; @@ -68,7 +74,7 @@ export interface ZoomableGroupProps { export interface GeographiesProps { disableOptimization?: boolean; geography?: string | { [key: string]: any } | string[]; - children?: (geographies: object[], projection: (point: Point) => void) => void; + children?: (geographies: object[], projection: GeoProjection) => void; } export interface GeographyProps { @@ -76,7 +82,7 @@ export interface GeographyProps { precision?: number; round?: boolean; geography?: object; - projection?: (point: Point) => void; + projection?: GeoProjection; tabable?: boolean; style?: { default?: React.CSSProperties; From 99e1ab424a3528d5531ad40cfa25b422ace5b9d1 Mon Sep 17 00:00:00 2001 From: Andrej Mihajlov Date: Wed, 30 Jan 2019 18:00:33 +0100 Subject: [PATCH 209/312] Use interface instead of type --- types/react-simple-maps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-simple-maps/index.d.ts b/types/react-simple-maps/index.d.ts index 4c63f28c69..955bc48279 100644 --- a/types/react-simple-maps/index.d.ts +++ b/types/react-simple-maps/index.d.ts @@ -21,7 +21,7 @@ export interface Line { }; } -export type ProjectionConfig = { +export interface ProjectionConfig { scale: number; xOffset: number; yOffset: number; From 71065960d5bc549843b9f4514bd48982a0b0c16c Mon Sep 17 00:00:00 2001 From: Andrej Mihajlov Date: Wed, 30 Jan 2019 18:15:24 +0100 Subject: [PATCH 210/312] Remove unnecessary semicolon --- types/react-simple-maps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-simple-maps/index.d.ts b/types/react-simple-maps/index.d.ts index 955bc48279..49e392035d 100644 --- a/types/react-simple-maps/index.d.ts +++ b/types/react-simple-maps/index.d.ts @@ -27,7 +27,7 @@ export interface ProjectionConfig { yOffset: number; rotation: [number, number, number]; precision: number; -}; +} export type ProjectionFunction = (width: number, height: number, config: ProjectionConfig) => GeoProjection; From 66a5b40176945ee85e47661d4adc90cea168b681 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Wed, 30 Jan 2019 09:22:57 -0800 Subject: [PATCH 211/312] Note errors for EnhancedLocation.addAsync --- types/office-js-preview/index.d.ts | 8 ++++++++ types/office-js/index.d.ts | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 56415c63cd..0516d08034 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -9427,6 +9427,10 @@ declare namespace Office { * * * + * + * + * + * *
    {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
    ErrorsInvalidFormatError - The format of the specified data object is not valid.
    * * In addition to this signature, this method also has the following signatures: @@ -9457,6 +9461,10 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} * Compose * + * + * Errors + * InvalidFormatError - The format of the specified data object is not valid. + * * * * @param locationIdentifiers The locations to be added to the current list of locations. diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 1ff4d05df3..eec0893859 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -9427,6 +9427,10 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} * Compose * + * + * Errors + * InvalidFormatError - The format of the specified data object is not valid. + * * * * In addition to this signature, this method also has the following signatures: @@ -9457,6 +9461,10 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} * Compose * + * + * Errors + * InvalidFormatError - The format of the specified data object is not valid. + * * * * @param locationIdentifiers The locations to be added to the current list of locations. From d0317950e5b287ad17d4a10afb9582545e0d0ddd Mon Sep 17 00:00:00 2001 From: Aleksandar Manukov <34056917+aleksandar-manukov@users.noreply.github.com> Date: Wed, 30 Jan 2019 19:34:58 +0200 Subject: [PATCH 212/312] Renaming bootstrap-colorpicker-v2 to bootstrap-colorpicker --- .../bootstrap-colorpicker-tests.ts} | 0 .../index.d.ts | 0 .../tsconfig.json | 2 +- .../tslint.json | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename types/{bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts => bootstrap-colorpicker/bootstrap-colorpicker-tests.ts} (100%) rename types/{bootstrap-colorpicker-v2 => bootstrap-colorpicker}/index.d.ts (100%) rename types/{bootstrap-colorpicker-v2 => bootstrap-colorpicker}/tsconfig.json (91%) rename types/{bootstrap-colorpicker-v2 => bootstrap-colorpicker}/tslint.json (100%) diff --git a/types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts b/types/bootstrap-colorpicker/bootstrap-colorpicker-tests.ts similarity index 100% rename from types/bootstrap-colorpicker-v2/bootstrap-colorpicker-v2-tests.ts rename to types/bootstrap-colorpicker/bootstrap-colorpicker-tests.ts diff --git a/types/bootstrap-colorpicker-v2/index.d.ts b/types/bootstrap-colorpicker/index.d.ts similarity index 100% rename from types/bootstrap-colorpicker-v2/index.d.ts rename to types/bootstrap-colorpicker/index.d.ts diff --git a/types/bootstrap-colorpicker-v2/tsconfig.json b/types/bootstrap-colorpicker/tsconfig.json similarity index 91% rename from types/bootstrap-colorpicker-v2/tsconfig.json rename to types/bootstrap-colorpicker/tsconfig.json index 7b9bf6cb2b..6b8f8a5d47 100644 --- a/types/bootstrap-colorpicker-v2/tsconfig.json +++ b/types/bootstrap-colorpicker/tsconfig.json @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "bootstrap-colorpicker-v2-tests.ts" + "bootstrap-colorpicker-tests.ts" ] } diff --git a/types/bootstrap-colorpicker-v2/tslint.json b/types/bootstrap-colorpicker/tslint.json similarity index 100% rename from types/bootstrap-colorpicker-v2/tslint.json rename to types/bootstrap-colorpicker/tslint.json From e58ab2b3b48facaf7b4d5f42591da8030f36df24 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Wed, 30 Jan 2019 09:51:46 -0800 Subject: [PATCH 213/312] Fix typos --- types/office-js-preview/index.d.ts | 6 +++--- types/office-js/index.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 0516d08034..a538a0f6c9 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -5181,7 +5181,7 @@ declare namespace Office { setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** - * Represents the data in a table or a {@link Office.TableBinding}. + * Represents the data in a table or an {@link Office.TableBinding}. * * @remarks * @@ -11108,7 +11108,7 @@ declare namespace Office { * Gets the locations of an appointment. * * The enhancedLocation property returns an {@link Office.EnhancedLocation} object that allows you to get the set of locations (each represented by - * a {@link Office.LocationDetails} object) associated with the appointment. + * an {@link Office.LocationDetails} object) associated with the appointment. * * [Api set: Mailbox Preview] * @@ -13389,7 +13389,7 @@ declare namespace Office { * Provides access to the Cc (carbon copy) recipients of a message. The type of object and level of access depends on the mode of the * current item. * - * The cc property returns a {@link Office.Recipients} object that provides methods to get or update the recipients on the Cc line of + * The cc property returns an {@link Office.Recipients} object that provides methods to get or update the recipients on the Cc line of * the message. * * [Api set: Mailbox 1.0] diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index eec0893859..139707e367 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -5181,7 +5181,7 @@ declare namespace Office { setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** - * Represents the data in a table or a {@link Office.TableBinding}. + * Represents the data in a table or an {@link Office.TableBinding}. * * @remarks *
    HostsExcel, Word
    @@ -11108,7 +11108,7 @@ declare namespace Office { * Gets the locations of an appointment. * * The enhancedLocation property returns an {@link Office.EnhancedLocation} object that allows you to get the set of locations (each represented by - * a {@link Office.LocationDetails} object) associated with the appointment. + * an {@link Office.LocationDetails} object) associated with the appointment. * * [Api set: Mailbox Preview] * @@ -13389,7 +13389,7 @@ declare namespace Office { * Provides access to the Cc (carbon copy) recipients of a message. The type of object and level of access depends on the mode of the * current item. * - * The cc property returns a {@link Office.Recipients} object that provides methods to get or update the recipients on the Cc line of + * The cc property returns an {@link Office.Recipients} object that provides methods to get or update the recipients on the Cc line of * the message. * * [Api set: Mailbox 1.0] From 6e2619fca4573d0f62913149c421f5d62da8919c Mon Sep 17 00:00:00 2001 From: Dan <32849715+ddangelo-shoprunner@users.noreply.github.com> Date: Wed, 30 Jan 2019 13:05:19 -0500 Subject: [PATCH 214/312] auth0-js - Added back needed fields back to Auth0DecodedHash Auth0Error can happen where Auth0 still uses these other fields that someone mistakenly removed a couple months ago (in cases like webAuth.login method). Responses aren't always in format 'error' & 'errorDescription' and the other fields need to be captured. Example response = HTTP 401 `{"name":"ValidationError","code":"invalid_user_password","description":"Wrong email or password.","statusCode":400}` Oct commit that mistakenly removed these https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c5b6a5e2d5403265f5aa9e0dc3d7f4498622703b#diff-7795f2501af1276ff905e366093a998b --- types/auth0-js/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 4fcbb5df33..b36a25db44 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -569,6 +569,14 @@ export type SpecErrorCodes = export interface Auth0Error { error: LibErrorCodes | SpecErrorCodes | string; errorDescription: string; + // Need to include non-intuitive error fields that Auth0 uses + code?: string; + description?: string; + name?: string; + policy?: string; + original?: any; + statusCode?: number; + statusText?: string; } export type Auth0ParseHashError = Auth0Error & { From 4bdbccfedcb7ce25924a17d33805edec190aeb35 Mon Sep 17 00:00:00 2001 From: Jim Geurts Date: Wed, 30 Jan 2019 10:06:22 -0600 Subject: [PATCH 215/312] Add asn1 --- types/asn1/asn1-tests.ts | 88 +++++++++++++++++++++++++++ types/asn1/index.d.ts | 126 +++++++++++++++++++++++++++++++++++++++ types/asn1/tsconfig.json | 25 ++++++++ types/asn1/tslint.json | 3 + 4 files changed, 242 insertions(+) create mode 100644 types/asn1/asn1-tests.ts create mode 100644 types/asn1/index.d.ts create mode 100644 types/asn1/tsconfig.json create mode 100644 types/asn1/tslint.json diff --git a/types/asn1/asn1-tests.ts b/types/asn1/asn1-tests.ts new file mode 100644 index 0000000000..f37541b03e --- /dev/null +++ b/types/asn1/asn1-tests.ts @@ -0,0 +1,88 @@ +import { Ber, BerReader, BerWriter } from 'asn1'; + +let buf: Buffer = Buffer.alloc(0); +let bool = false; +let str = ''; +let num = 0; +let numOrNull: number | null = 0; +const roStrArray: ReadonlyArray = [str]; + +const reader = new BerReader(buf); +numOrNull = reader.peek(); +bool = reader.readBoolean(); +numOrNull = reader.readByte(bool); +num = reader.readEnumeration(); +num = reader.readInt(); +num = reader.readLength(); +num = reader.readLength(num); +str = reader.readOID(); +str = reader.readOID(num); +numOrNull = reader.readSequence(); +numOrNull = reader.readSequence(num); +str = reader.readString(); +str = reader.readString(num); +buf = reader.readString(num, bool); +num = reader._readTag(); +num = reader._readTag(num); + +let writer = new BerWriter(); +writer = new BerWriter({ + size: num, + growthFactor: num, +}); + +buf = writer.buffer; +buf = writer._buf; +num = writer._size; +num = writer._offset; + +writer.endSequence(); +writer.startSequence(); +writer.startSequence(num); +writer.writeBoolean(bool); +writer.writeBoolean(bool, num); +writer.writeBuffer(buf, num); +writer.writeByte(num); +writer.writeEnumeration(num); +writer.writeEnumeration(num, num); +writer.writeInt(num); +writer.writeInt(num, num); +writer.writeLength(num); +writer.writeNull(); +writer.writeOID(str, num); +writer.writeString(str); +writer.writeString(str, num); +writer.writeStringArray(roStrArray); +writer._ensure(num); + +num = Ber.BMPString; +num = Ber.BitString; +num = Ber.Boolean; +num = Ber.CharacterString; +num = Ber.Constructor; +num = Ber.Context; +num = Ber.EOC; +num = Ber.Enumeration; +num = Ber.External; +num = Ber.GeneralString; +num = Ber.GeneralizedTime; +num = Ber.GraphicString; +num = Ber.IA5String; +num = Ber.Integer; +num = Ber.Null; +num = Ber.NumericString; +num = Ber.OID; +num = Ber.ObjectDescriptor; +num = Ber.OctetString; +num = Ber.PDV; +num = Ber.PrintableString; +num = Ber.Real; +num = Ber.RelativeOID; +num = Ber.Sequence; +num = Ber.Set; +num = Ber.T61String; +num = Ber.UTCTime; +num = Ber.UniversalString; +num = Ber.Utf8String; +num = Ber.VideotexString; +num = Ber.VisibleString; diff --git a/types/asn1/index.d.ts b/types/asn1/index.d.ts new file mode 100644 index 0000000000..3f7de44af8 --- /dev/null +++ b/types/asn1/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for asn1 0.2 +// Project: https://github.com/joyent/node-asn1 +// Definitions by: Jim Geurts +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +export class BerReader { + readonly buffer: Buffer; + readonly offset: number; + readonly length: number; + readonly remain: number; + readonly _buf: Buffer; + _size: number; + _offset: number; + + constructor(data: Buffer); + + peek(): number | null; + readBoolean(): boolean; + readByte(peek: boolean): number | null; + readEnumeration(): number; + readInt(): number; + readLength(offset?: number): number; + readOID(tag?: number): string; + readSequence(tag?: number): number | null; + readString(tag?: number): string; + readString(tag: number, retbuf: boolean): Buffer; + _readTag(tag?: number): number; +} + +export class BerWriter { + readonly buffer: Buffer; + readonly _buf: Buffer; + readonly _size: number; + _offset: number; + + constructor(options?: { + size: number; + growthFactor: number; + }); + + endSequence(): void; + startSequence(tag?: number): void; + writeBoolean(b: boolean, tag?: number): void; + writeBuffer(buf: Buffer, tag: number): void; + writeByte(b: number): void; + writeEnumeration(i: number, tag?: number): void; + writeInt(i: number, tag?: number): void; + writeLength(len: number): void; + writeNull(): void; + writeOID(s: string, tag: number): void; + writeString(s: string, tag?: number): void; + writeStringArray(strings: ReadonlyArray): void; + _ensure(length: number): void; +} + +export namespace Ber { + const BMPString: number; + const BitString: number; + const Boolean: number; + const CharacterString: number; + const Constructor: number; + const Context: number; + const EOC: number; + const Enumeration: number; + const External: number; + const GeneralString: number; + const GeneralizedTime: number; + const GraphicString: number; + const IA5String: number; + const Integer: number; + const Null: number; + const NumericString: number; + const OID: number; + const ObjectDescriptor: number; + const OctetString: number; + const PDV: number; + const PrintableString: number; + const Real: number; + const RelativeOID: number; + const Sequence: number; + const Set: number; + const T61String: number; + const UTCTime: number; + const UniversalString: number; + const Utf8String: number; + const VideotexString: number; + const VisibleString: number; +} +/* +declare enum BerType { + EOC = 0, + Boolean = 1, + Integer = 2, + BitString = 3, + OctetString = 4, + Null = 5, + OID = 6, + ObjectDescriptor = 7, + External = 8, + Real = 9, // float + Enumeration = 10, + PDV = 11, + Utf8String = 12, + RelativeOID = 13, + Sequence = 16, + Set = 17, + NumericString = 18, + PrintableString = 19, + T61String = 20, + VideotexString = 21, + IA5String = 22, + UTCTime = 23, + GeneralizedTime = 24, + GraphicString = 25, + VisibleString = 26, + GeneralString = 28, + UniversalString = 29, + CharacterString = 30, + BMPString = 31, + Constructor = 32, + Context = 128, +} + +*/ diff --git a/types/asn1/tsconfig.json b/types/asn1/tsconfig.json new file mode 100644 index 0000000000..fd1bdc45d9 --- /dev/null +++ b/types/asn1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedParameters": true, + + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asn1-tests.ts" + ] +} \ No newline at end of file diff --git a/types/asn1/tslint.json b/types/asn1/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/asn1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 4a875dfd9da6a0d8eb5fc91c2b7c3834aec739d5 Mon Sep 17 00:00:00 2001 From: Dan <32849715+ddangelo-shoprunner@users.noreply.github.com> Date: Wed, 30 Jan 2019 13:38:51 -0500 Subject: [PATCH 216/312] Removed trailing whitespaces --- types/auth0-js/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index b36a25db44..7e43da1c89 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -571,12 +571,12 @@ export interface Auth0Error { errorDescription: string; // Need to include non-intuitive error fields that Auth0 uses code?: string; - description?: string; + description?: string; name?: string; policy?: string; - original?: any; - statusCode?: number; - statusText?: string; + original?: any; + statusCode?: number; + statusText?: string; } export type Auth0ParseHashError = Auth0Error & { From c0af6b92377587815c2785623278256c8d62bbf7 Mon Sep 17 00:00:00 2001 From: Jules Janssen Date: Wed, 30 Jan 2019 20:05:55 +0100 Subject: [PATCH 217/312] [chart.js] add `precision` option to `LinearTickOptions` interface See [commit](https://github.com/chartjs/Chart.js/commit/9fbac8893865fc6f7efdab7f49d480e6a730c669#diff-bd4c401aafa9aaaa38640e15e4b2ecbc) and [docs](https://www.chartjs.org/docs/latest/axes/cartesian/linear.html) --- types/chart.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ca28a1a9f6..8e795ed77c 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -537,6 +537,7 @@ declare namespace Chart { interface LinearTickOptions extends TickOptions { maxTicksLimit?: number; stepSize?: number; + precision?: number; suggestedMin?: number; suggestedMax?: number; } From bdfc3ebeb582990a633fb00e29d735ee61780527 Mon Sep 17 00:00:00 2001 From: Leonardo Gatica Date: Wed, 30 Jan 2019 16:35:27 -0300 Subject: [PATCH 218/312] feat(typings): add semantic-release interfaces --- types/semantic-release/index.d.ts | 46 +++++++++++++++++++ .../semantic-release-tests.ts | 17 +++++++ types/semantic-release/tsconfig.json | 24 ++++++++++ types/semantic-release/tslint.json | 1 + 4 files changed, 88 insertions(+) create mode 100644 types/semantic-release/index.d.ts create mode 100644 types/semantic-release/semantic-release-tests.ts create mode 100644 types/semantic-release/tsconfig.json create mode 100644 types/semantic-release/tslint.json diff --git a/types/semantic-release/index.d.ts b/types/semantic-release/index.d.ts new file mode 100644 index 0000000000..656461b756 --- /dev/null +++ b/types/semantic-release/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for semantic-release 15.13 +// Project: https://github.com/semantic-release/semantic-release#readme +// Definitions by: Leonardo Gatica +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * The semantic release configuration itself. + */ +export interface GlobalConfig { + /** The full prepare step configuration. */ + prepare?: any; + /** The branch on which releases should happen. */ + branch: string; + /** The Git repository URL, in any supported format. */ + repositoryUrl: string; + /** The Git tag format used by semantic-release to identify releases. */ + tagFormat: string; +} + +export interface LastRelease { + /** The version name of the release */ + version: string; + /** The Git tag of the release. */ + gitTag: string; + /** The Git checksum of the last commit of the release. */ + gitHead: string; +} + +export interface NextRelease extends LastRelease { + /** The release notes of the next release. */ + notes: string; +} + +export interface Context { + /** The semantic release configuration itself. */ + options?: GlobalConfig; + /** The previous release details. */ + lastRelease?: LastRelease; + /** The next release details. */ + nextRelease?: NextRelease; + /** The shared logger instance of semantic release. */ + logger: { + log: (message: string, ...vars: any[]) => void, + error: (message: string, ...vars: any[]) => void, + }; +} diff --git a/types/semantic-release/semantic-release-tests.ts b/types/semantic-release/semantic-release-tests.ts new file mode 100644 index 0000000000..0c954fe295 --- /dev/null +++ b/types/semantic-release/semantic-release-tests.ts @@ -0,0 +1,17 @@ +import * as lib from 'semantic-release'; + +function publish(pluginConfig: any, context: lib.Context) { + const version = context.nextRelease && context.nextRelease.version; + context.logger.log(`New version ${version}`); +} + +const context = { + nextRelease: { + version: '1.0.0', + gitTag: '1.0.0', + gitHead: 'f1eed296d2ffe184fb15f52b1c5ad778f5c87645', + notes: 'New release' + }, + logger: console +}; +publish({}, context); diff --git a/types/semantic-release/tsconfig.json b/types/semantic-release/tsconfig.json new file mode 100644 index 0000000000..d226e296ce --- /dev/null +++ b/types/semantic-release/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "semantic-release-tests.ts" + ] +} diff --git a/types/semantic-release/tslint.json b/types/semantic-release/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/semantic-release/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9520a876d77f8b0d14a53155d01b2690c339f2f0 Mon Sep 17 00:00:00 2001 From: frontendmonster Date: Wed, 30 Jan 2019 23:22:39 +0330 Subject: [PATCH 219/312] Make MongooseDocument.invalidate value param optional --- types/mongoose/index.d.ts | 3 ++- types/mongoose/mongoose-tests.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b7d3b5d9c6..800b37f520 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -16,6 +16,7 @@ // Dan Manastireanu // stablio // Emmanuel Gautier +// Frontend Monster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1310,7 +1311,7 @@ declare module "mongoose" { * @param kind optional kind property for the error * @returns the current ValidationError, with all currently invalidated paths */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): Error.ValidationError | boolean; + invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): Error.ValidationError | boolean; /** Returns true if path was directly set and modified, else false. */ isDirectModified(path: string): boolean; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 8e6a60fdc7..30b5b51a84 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -726,6 +726,7 @@ doc.execPopulate().then(function (arg) { doc.get('path', Number); doc.init(doc).init(doc, {}); doc.inspect(); +doc.invalidate('path', new Error('hi')).toString(); doc.invalidate('path', new Error('hi'), 999).toString(); doc.isDirectModified('path').valueOf(); doc.isInit('path').valueOf(); From 8aa4e6316d2d82edba98824583175c5f946d32a4 Mon Sep 17 00:00:00 2001 From: licui Date: Wed, 30 Jan 2019 15:33:08 -0500 Subject: [PATCH 220/312] Add missing API functions in Window --- types/openfin/index.d.ts | 40 ++++++++++++++++++++++++++++++++-- types/openfin/openfin-tests.ts | 24 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 559a6318b3..5d2cd28742 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -66,12 +66,14 @@ declare namespace fin { type RuntimeInfo = import('./_v2/api/system/runtime-info').RuntimeInfo; type RVMInfo = import('./_v2/api/system/rvm').RVMInfo; type WindowDetail = import('./_v2/api/system/window').WindowDetail; - type WindowInfo = import('./_v2/api/system/window').WindowInfo; + type SystemWindowInfo = import('./_v2/api/system/window').WindowInfo; type AnchorType = import('./_v2/api/window/anchor-type').AnchorType; type Bounds = import('./_v2/api/window/bounds').default; type Transition = import('./_v2/api/window/transition').Transition; type TransitionOptions = import('./_v2/api/window/transition').TransitionOptions; type WindowOption = import('./_v2/api/window/windowOption').WindowOption; + type WindowInfo = import('./_v2/api/window/window').WindowInfo; + type FrameInfo = import('./_v2/api/window/window').FrameInfo; const desktop: OpenFinDesktop; @@ -574,7 +576,7 @@ declare namespace fin { /** * Retrieves an array of data (name, ids, bounds) for all application windows. */ - getAllWindows(callback?: (windowInfoList: WindowInfo[]) => void, errorCallback?: (reason: string) => void): void; + getAllWindows(callback?: (windowInfoList: SystemWindowInfo[]) => void, errorCallback?: (reason: string) => void): void; /** * Returns information about the app asset. */ @@ -825,6 +827,11 @@ declare namespace fin { * @param Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window. */ close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Executes Javascript on the window, restricted to windows you own or windows owned by applications you have created. + * @param code JavaScript code to be executed on the window. + */ + executeJavaScript(code: string, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Prevents a user from changing a window's size/position when using the window's frame. * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. @@ -849,6 +856,11 @@ declare namespace fin { * Gives focus to the window. */ focus(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of frame info objects representing the main frame and any + * iframes that are currently on the page. + */ + getAllFrames(callback?: (frames: FrameInfo[]) => void, errorCallback?: (reason: string) => void): void; /** * Gets the current bounds (top, left, width, height) of the window. */ @@ -858,6 +870,10 @@ declare namespace fin { * Please note that calling window is included in the result array. */ getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets an information object for the window. + */ + getInfo(callback?: (info: WindowInfo) => void, errorCallback?: (reason: string) => void): void; /** * Gets the current settings of the window. */ @@ -910,6 +926,22 @@ declare namespace fin { * Moves the window to a specified location. */ moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Navigates the window to a specified URL. + */ + navigate(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Navigates the window back one page. + */ + navigateBack(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Navigates the window forward one page. + */ + navigateForward(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Reloads the window current page. + */ + reload(ignoreCacheopt?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Removes a previously registered event listener from the specified event. */ @@ -962,6 +994,10 @@ declare namespace fin { * Stops the taskbar icon from flashing. */ stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Stops any current navigation the window is performing. + */ + stopNavigation(callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Updates the window using the passed options */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 134139ce2e..d1b8ebe32d 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -736,6 +736,8 @@ function test_window() { finWindow.bringToFront(); // close finWindow.close(); + // executeJavaScript + finWindow.executeJavaScript("console.log('Hello world');"); // disableFrame finWindow.disableFrame(); // enableFrame @@ -744,10 +746,22 @@ function test_window() { finWindow.flash(); // focus finWindow.focus(); + // getAllFrames + finWindow.getAllFrames(frames => { + console.log(`name: ${frames[0].name} uuid: ${frames[0].uuid}`); + }); // getBounds finWindow.getBounds(bounds => { console.log(`top: ${bounds.top} left: ${bounds.left} height: ${bounds.height} width: ${bounds.width}`); }); + // getGroups + finWindow.getGroup(windowGroup => { + console.log(`There are a total of ${windowGroup.length} windows in this group.`); + }); + // getInfo + finWindow.getInfo(info => { + console.log(`Window title: ${info.title}`); + }); // getOptions finWindow.getOptions(options => { console.log(options); @@ -830,6 +844,14 @@ function test_window() { finWindow.moveBy(10, 10); // moveTo finWindow.moveTo(100, 200); + // navigate + finWindow.navigate("https://openfin.co"); + // navigateBack + finWindow.navigateBack(); + // navigateForward + finWindow.navigateForward(); + // reload + finWindow.reload(); // removeEventListener finWindow.removeEventListener("bounds-changed", event => { console.log(event); @@ -852,6 +874,8 @@ function test_window() { finWindow.showAt(10, 10, false); // stopFlashing finWindow.stopFlashing(); + // stopNavigation + finWindow.stopNavigation(); // updateOptions finWindow.updateOptions({ frame: false, From f50be0da11152edd00fa4b16e908ccb818784998 Mon Sep 17 00:00:00 2001 From: Andres Kalle Date: Wed, 30 Jan 2019 22:51:08 +0200 Subject: [PATCH 221/312] nodegit: Fix return type of Repository#createBlobFromBuffer --- types/nodegit/nodegit-tests.ts | 2 ++ types/nodegit/repository.d.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/nodegit/nodegit-tests.ts b/types/nodegit/nodegit-tests.ts index 1732844d1c..a908f8a58f 100644 --- a/types/nodegit/nodegit-tests.ts +++ b/types/nodegit/nodegit-tests.ts @@ -62,3 +62,5 @@ const signature = Git.Signature.now("name", "email"); signature.name(); signature.email(); signature.when(); + +repo.createBlobFromBuffer(Buffer.from("test")).then((oid: Git.Oid) => oid.cpy()); diff --git a/types/nodegit/repository.d.ts b/types/nodegit/repository.d.ts index 6066f770b2..d74b39834d 100644 --- a/types/nodegit/repository.d.ts +++ b/types/nodegit/repository.d.ts @@ -153,7 +153,7 @@ export class Repository { /** * Create a blob from a buffer */ - createBlobFromBuffer(buffer: Buffer): Oid; + createBlobFromBuffer(buffer: Buffer): Promise; treeBuilder(tree: Tree): Promise; /** * Gets the default signature for the default user and now timestamp From fc452ce40e2d3b4cf3bc7398fa4e866190cfcb82 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 02:15:16 -0800 Subject: [PATCH 222/312] node-forge: Complete pkcs12 with toPkcs12Asn1, generateKey Signed-off-by: Anders Kaseorg --- types/node-forge/index.d.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 67e12c35bd..bff251912a 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -495,6 +495,30 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; + + function toPkcs12Asn1( + key: pki.PrivateKey, + cert: pki.Certificate | pki.Certificate[], + password: string | null, + options?: { + algorithm?: 'aes128' | 'aes192' | 'aes256' | '3des', + count?: number, + saltSize?: number, + useMac?: boolean, + localKeyId?: Hex, + friendlyName?: string, + generateLocalKeyId?: boolean, + }, + ): asn1.Asn1; + + function generateKey( + password: string | null | undefined, + salt: util.ByteBuffer, + id: Byte, + iter: number, + n: number, + md?: md.MessageDigest, + ): util.ByteBuffer; } namespace pkcs7 { From 58ef2b85bc884ec32074c5df5e225d825671c7d1 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 02:25:52 -0800 Subject: [PATCH 223/312] node-forge: pki.createCaStore accepts an optional array of certificates Signed-off-by: Anders Kaseorg --- types/node-forge/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index bff251912a..9cdda89c92 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -69,7 +69,7 @@ declare module "node-forge" { function privateKeyFromPem(pem: PEM): PrivateKey; function certificateToPem(cert: Certificate, maxline?: number): PEM; function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; - function createCaStore(): CAStore; + function createCaStore(certs?: ReadonlyArray): CAStore; function verifyCertificateChain(caStore: CAStore, chain: Certificate[], customVerifyCallback?: (verified: boolean | string, depth: number, chain: Certificate[]) => boolean): boolean; interface oids { From 8d693d60257a5363016d69dbf95c70c9309f9b4a Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 02:20:06 -0800 Subject: [PATCH 224/312] node-forge: Add tls Signed-off-by: Anders Kaseorg --- types/node-forge/index.d.ts | 281 ++++++++++++++++++++++++++++++++++++ 1 file changed, 281 insertions(+) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 9cdda89c92..ad15411714 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -9,6 +9,7 @@ // Nikita Koryabkin // timhwang21 // supaiku0 +// Anders Kaseorg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -607,4 +608,284 @@ declare module "node-forge" { function create(any: any): any; } } + + namespace tls { + interface ProtocolVersion { + major: Byte; + minor: Byte; + } + + const Versions: ProtocolVersion[]; + const SupportedVersions: ProtocolVersion[]; + const Version: ProtocolVersion; + + const MaxFragment: number; + + enum ConnectionEnd { + server = 0, + client = 1, + } + + enum PRFAlgorithm { + tls_prf_sha256 = 0, + } + + enum BulkCipherAlgorithm { + rc4 = 0, + des3 = 1, + aes = 2, + } + + enum CipherType { + stream = 0, + block = 1, + aead = 2, + } + + enum MACAlgorithm { + hmac_md5 = 0, + hmac_sha1 = 1, + hmac_sha256 = 2, + hmac_sha384 = 3, + hmac_sha512 = 4, + } + + enum CompressionMethod { + none = 0, + deflate = 1, + } + + enum ContentType { + change_cipher_spec = 20, + alert = 21, + handshake = 22, + application_data = 23, + heartbeat = 24, + } + + enum HandshakeType { + hello_request = 0, + client_hello = 1, + server_hello = 2, + certificate = 11, + server_key_exchange = 12, + certificate_request = 13, + server_hello_done = 14, + certificate_verify = 15, + client_key_exchange = 16, + finished = 20, + } + + namespace Alert { + enum Level { + warning = 1, + fatal = 2, + } + + enum Description { + close_notify = 0, + unexpected_message = 10, + bad_record_mac = 20, + decryption_failed = 21, + record_overflow = 22, + decompression_failure = 30, + handshake_failure = 40, + bad_certificate = 42, + unsupported_certificate = 43, + certificate_revoked = 44, + certificate_expired = 45, + certificate_unknown = 46, + illegal_parameter = 47, + unknown_ca = 48, + access_denied = 49, + decode_error = 50, + decrypt_error = 51, + export_restriction = 60, + protocol_version = 70, + insufficient_security = 71, + internal_error = 80, + user_canceled = 90, + no_renegotiation = 100, + } + } + + enum HeartbeatMessageType { + heartbeat_request = 1, + heartbeat_response = 2, + } + + interface CipherSuite { + id: [Byte, Byte]; + name: string; + } + + const CipherSuites: { [name: string]: CipherSuite }; + + interface CertificateRequest { + certificate_types: util.ByteBuffer; + certificate_authorities: util.ByteBuffer; + } + + type ConnectionState = any; + + interface Connection { + version: ProtocolVersion; + entity: ConnectionEnd; + sessionId: Bytes | null; + caStore: pki.CAStore; + sessionCache: SessionCache | null; + cipherSuites: CipherSuite[]; + connected(conn: Connection): void; + virtualHost: string | null; + verifyClient: boolean; + verify( + conn: Connection, + verified: Verified, + depth: number, + certs: pki.Certificate[] + ): Verified; + getCertificate: + | (( + conn: Connection, + hint: CertificateRequest | string[] + ) => pki.PEM | ReadonlyArray) + | null; + getPrivateKey: + | ((conn: Connection, certificate: pki.Certificate) => pki.PEM) + | null; + getSignature: + | (( + conn: Connection, + bytes: Bytes, + callback: (conn: Connection, bytes: Bytes) => void + ) => void) + | null; + input: util.ByteBuffer; + tlsData: util.ByteBuffer; + data: util.ByteBuffer; + tlsDataReady(conn: Connection): void; + dataReady(conn: Connection): void; + heartbeatReceived: + | ((conn: Connection, payload: util.ByteBuffer) => void) + | undefined; + closed(conn: Connection): void; + error(conn: Connection, error: TLSError): void; + deflate: ((inBytes: Bytes) => Bytes) | null; + inflate: ((inBytes: Bytes) => Bytes) | null; + reset(clearFail?: boolean): void; + record: Record | null; + session: Session | null; + peerCertificate: pki.Certificate | null; + state: { pending: ConnectionState | null; current: ConnectionState }; + expect: number; + fragmented: Record | null; + records: Record[]; + open: boolean; + handshakes: number; + handshaking: boolean; + isConnected: boolean; + fail: boolean; + handshake(sessionId?: Bytes | null): void; + process(data: Bytes): number; + prepare(data: Bytes): boolean; + prepareHeartbeatRequest( + payload: Bytes | util.ByteBuffer, + payloadLength?: number + ): boolean; + close(clearFail?: boolean): Connection; + } + + interface Record { + type: ContentType; + version: ProtocolVersion; + length: number; + fragment: util.ByteBuffer; + ready?: boolean; + } + + interface Session { + version: ProtocolVersion | null; + extensions: { [_: string]: object }; + cipherSuite: CipherSuite | null; + compressionMethod: CompressionMethod | null; + serverCertificate: pki.Certificate | null; + clientCertificate: pki.Certificate | null; + md5: md.MessageDigest; + sha1: md.MessageDigest; + } + + interface SessionCache { + cache: { [key: string]: Session }; + capacity: number; + order: [Hex]; + getSession(sessionId: Bytes): Session; + setSession(sessionId: Bytes, session: Session): void; + } + + function createSessionCache( + cache?: SessionCache | { [key: string]: Session }, + capacity?: number + ): SessionCache; + + interface Alert { + level: Alert.Level; + description: Alert.Description; + } + + interface TLSError extends Error { + message: string; + send: boolean; + origin: "server" | "client"; + alert: Alert; + } + + type Verified = true | { message?: string; alert?: Alert.Description }; + + function createConnection(options: { + server?: boolean; + sessionId?: Bytes | null; + caStore?: pki.CAStore | ReadonlyArray; + sessionCache?: SessionCache | { [key: string]: Session }; + cipherSuites?: CipherSuite[]; + connected(conn: Connection): void; + virtualHost?: string; + verifyClient?: boolean; + verify?( + conn: Connection, + verified: Verified, + depth: number, + certs: pki.Certificate[] + ): Verified; + getCertificate?( + conn: Connection, + hint: CertificateRequest | string[] + ): pki.PEM | ReadonlyArray; + getPrivateKey?(conn: Connection, certificate: pki.Certificate): pki.PEM; + getSignature?( + conn: Connection, + bytes: Bytes, + callback: (conn: Connection, bytes: Bytes) => void + ): void; + tlsDataReady(conn: Connection): void; + dataReady(conn: Connection): void; + heartbeatReceived?(conn: Connection, payload: util.ByteBuffer): void; + closed(conn: Connection): void; + error(conn: Connection, error: TLSError): void; + deflate?(inBytes: Bytes): Bytes; + inflate?(inBytes: Bytes): Bytes; + }): Connection; + + function prf_tls1( + secret: string, + label: string, + seed: string, + length: number + ): util.ByteBuffer; + + function hmac_sha1( + key: string | ReadonlyArray | util.ByteBuffer, + seqNum: [number, number], + record: Record + ): Bytes; + } } From 5b070eaaa859a38994a576fddd2d22ed0c6f40fb Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Wed, 30 Jan 2019 03:17:00 -0800 Subject: [PATCH 225/312] node-forge: Add test for tls Signed-off-by: Anders Kaseorg --- types/node-forge/node-forge-tests.ts | 121 ++++++++++++++++++++++++++- 1 file changed, 119 insertions(+), 2 deletions(-) diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 8cb1e54aea..c99f417550 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -207,7 +207,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin { const emptyStore = forge.pki.createCaStore(); - const certificate = forge.pki.createCertificate(); + const certificate = cert; const pem = forge.pki.certificateToPem(certificate); const caStore = forge.pki.createCaStore(); @@ -225,4 +225,121 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin { const key: string = forge.pkcs5.pbkdf2("password", "salt", 1000, 32); -} \ No newline at end of file +} + +{ + // Based on node-forge/examples/tls.js + + let success = false; + + const client = forge.tls.createConnection({ + server: false, + caStore: [cert], + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + virtualHost: 'server', + verify: function(c, verified, depth, certs) { + console.log( + 'TLS Client verifying certificate w/CN: \"' + + certs[0].subject.getField('CN').value + + '\", verified: ' + verified + '...'); + return verified; + }, + connected: function(c) { + console.log('Client connected...'); + + // send message to server + setTimeout(function() { + c.prepareHeartbeatRequest('heartbeat'); + c.prepare('Hello Server'); + }, 1); + }, + getCertificate: function(c, hint) { + console.log('Client getting certificate ...'); + return forge.pki.certificateToPem(cert); + }, + getPrivateKey: function(c, cert) { + return privateKeyPem; + }, + tlsDataReady: function(c) { + // send TLS data to server + server.process(c.tlsData.getBytes()); + }, + dataReady: function(c) { + var response = c.data.getBytes(); + console.log('Client received \"' + response + '\"'); + success = (response === 'Hello Client'); + c.close(); + }, + heartbeatReceived: function(c, payload) { + console.log('Client received heartbeat: ' + payload.getBytes()); + }, + closed: function(c) { + console.log('Client disconnected.'); + if(success) { + console.log('PASS'); + } else { + console.log('FAIL'); + } + }, + error: function(c, error) { + console.log('Client error: ' + error.message); + } + }); + + // create TLS server + const server = forge.tls.createConnection({ + server: true, + caStore: [cert], + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + connected: function(c) { + console.log('Server connected'); + c.prepareHeartbeatRequest('heartbeat'); + }, + verifyClient: true, + verify: function(c, verified, depth, certs) { + console.log( + 'Server verifying certificate w/CN: \"' + + certs[0].subject.getField('CN').value + + '\", verified: ' + verified + '...'); + return verified; + }, + getCertificate: function(c, hint) { + console.log('Server getting certificate for \"' + (hint as string[])[0] + '\"...'); + return forge.pki.certificateToPem(cert); + }, + getPrivateKey: function(c, cert) { + return privateKeyPem; + }, + tlsDataReady: function(c) { + // send TLS data to client + client.process(c.tlsData.getBytes()); + }, + dataReady: function(c) { + console.log('Server received \"' + c.data.getBytes() + '\"'); + + // send response + c.prepare('Hello Client'); + c.close(); + }, + heartbeatReceived: function(c, payload) { + console.log('Server received heartbeat: ' + payload.getBytes()); + }, + closed: function(c) { + console.log('Server disconnected.'); + }, + error: function(c, error) { + console.log('Server error: ' + error.message); + } + }); + + console.log('created TLS client and server, doing handshake...'); + client.handshake(); +} From f5b254a3d564a4363b8106c4b4ca8f1d2f917036 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Wed, 30 Jan 2019 12:56:54 -0800 Subject: [PATCH 226/312] Tweak LocationType description --- types/office-js-preview/index.d.ts | 2 +- types/office-js/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index a538a0f6c9..ea3a2d76f4 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -7714,7 +7714,7 @@ declare namespace Office { Appointment = "appointment" } /** - * Specifies an appointment's location type. + * Specifies an appointment location's type. * * [Api set: Mailbox Preview] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 139707e367..f2616ffbef 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -7714,7 +7714,7 @@ declare namespace Office { Appointment = "appointment" } /** - * Specifies an appointment's location type. + * Specifies an appointment location's type. * * [Api set: Mailbox Preview] * From 312d6d4dc98faa2416c99db718284d200f8f78c3 Mon Sep 17 00:00:00 2001 From: Drew Wyatt Date: Wed, 30 Jan 2019 16:32:08 -0500 Subject: [PATCH 227/312] added cast event --- types/jwplayer/index.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 05d9c50aa6..f02159bc6f 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -7,6 +7,7 @@ // Benjamin Dobson // Be Birchall // Daniel Cassidy +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -264,6 +265,13 @@ declare namespace jwplayer { reason: 'auto' | 'api' | 'initial choice'; } + interface CastParam { + available: boolean; + active: boolean; + deviceName: string; + type: 'cast'; + } + interface EventParams { adClick: AdProgressParam; adCompanions: AdCompanionsParam; @@ -277,6 +285,7 @@ declare namespace jwplayer { adPlay: AdPlayParam; adPause: AdPlayParam; adTime: AdTimeParam; + cast: CastParam; meta: MetadataParam; audioTracks: AudioTracksParam; audioTrackChanged: AudioTrackChangedParam; From 8e96c7b4455a9c1ac5a16ae1b20ef9d24deef7b6 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 30 Jan 2019 13:51:17 -0800 Subject: [PATCH 228/312] Adding descriptions to async overloads --- types/office-js-preview/index.d.ts | 1844 +++++++++++++++++++++++++++- types/office-js/index.d.ts | 1844 +++++++++++++++++++++++++++- 2 files changed, 3658 insertions(+), 30 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 75e9ed910f..34ab184434 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -1093,6 +1093,104 @@ declare namespace Office { * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. */ displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + /** + * Displays a dialog to show or collect information from the user or to facilitate Web navigation. + * + * @remarks + *
    HostsExcel, Word
    + * + *
    HostsWord, Excel, Outlook, PowerPoint
    Requirement setsDialogApi, Mailbox 1.4
    + * + * This method is available in the DialogApi requirement set for Word, Excel, or PowerPoint add-ins, and in the Mailbox requirement set 1.4 + * for Outlook. For more on how to specify a requirement set in your manifest, see + * {@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements | Specify Office hosts and API requirements}. + * + * The initial page must be on the same domain as the parent page (the startAddress parameter). After the initial page loads, you can go to + * other domains. + * + * Any page calling `office.context.ui.messageParent` must also be on the same domain as the parent page. + * + * **Design considerations**: + * + * The following design considerations apply to dialog boxes: + * + * - An Office Add-in task pane can have only one dialog box open at any time. Multiple dialogs can be open at the same time from Add-in + * Commands (custom ribbon buttons or menu items). + * + * - Every dialog box can be moved and resized by the user. + * + * - Every dialog box is centered on the screen when opened. + * + * - Dialog boxes appear on top of the host application and in the order in which they were created. + * + * Use a dialog box to: + * + * - Display authentication pages to collect user credentials. + * + * - Display an error/progress/input screen from a ShowTaskpane or ExecuteAction command. + * + * - Temporarily increase the surface area that a user has available to complete a task. + * + * Do not use a dialog box to interact with a document. Use a task pane instead. + * + * For a design pattern that you can use to create a dialog box, see + * {@link https://github.com/OfficeDev/Office-Add-in-UX-Design-Patterns/blob/master/Patterns/Client_Dialog.md | Client Dialog} in the Office + * Add-in UX Design Patterns repository on GitHub. + * + * **displayDialogAsync Errors**: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Code numberMeaning
    12004The domain of the URL passed to displayDialogAsync is not trusted. The domain must be either the same domain as the host page (including protocol and port number), or it must be registered in the section of the add-in manifest.
    12005The URL passed to displayDialogAsync uses the HTTP protocol. HTTPS is required. (In some versions of Office, the error message returned with 12005 is the same one returned for 12004.)
    12007A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time.
    12009The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog.
    + * + * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the + * following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to
    AsyncResult.valueAccess the Dialog object.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextAccess your user-defined object or value, if you passed one as the asyncContext parameter.
    + * + * @param startAddress - Accepts the initial HTTPS URL that opens in the dialog. + * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. + */ displayDialogAsync(startAddress: string, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. @@ -2291,6 +2389,17 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Adds an event handler to the object for the specified {@link Office.EventType}. Supported EventTypes are + * `Office.EventType.BindingDataChanged` and `Office.EventType.BindingSelectionChanged`. + * + * @remarks + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.BindingDataChangedEventArgs} or {@link Office.BindingSelectionChangedEventArgs}. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => void): void; /** * Returns the data contained within the binding. @@ -2307,6 +2416,19 @@ declare namespace Office { * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. */ getDataAsync(options?: GetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Returns the data contained within the binding. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * When called from a MatrixBinding or TableBinding, the getDataAsync method will return a subset of the bound values if the optional startRow, + * startColumn, rowCount, and columnCount parameters are specified (and they specify a contiguous and valid range). + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the values in the specified binding. + * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. + */ getDataAsync(callback?: (result: AsyncResult) => void): void; /** * Removes the specified handler from the binding for the specified event type. @@ -2319,6 +2441,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes the specified handler from the binding for the specified event type. + * + * @remarks + *
    Requirement SetsBindingEvents
    + * + * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes data to the bound section of the document represented by the specified binding object. @@ -2451,6 +2582,134 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Writes data to the bound section of the document represented by the specified binding object. + * + * @remarks + * + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * The value passed for data contains the data to be written in the binding. The kind of value passed determines what will be written as + * described in the following table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringPlain text or anything that can be coerced to a string will be written.
    An array of arrays ("matrix")Tabular data without headers will be written. For example, to write data to three rows in two columns, you can pass an array like this: `[["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]`. To write a single column of three rows, pass an array like this: `[["R1C1"], ["R2C1"], ["R3C1"]]`.
    An {@link Office.TableData} objectA table with headers will be written.
    + * + * Additionally, these application-specific actions apply when writing data to a binding. For Word, the specified data is written to the + * binding as follows: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringThe specified text is written.
    An array of arrays ("matrix") or an {@link Office.TableData} objectA Word table is written.
    HTMLThe specified HTML is written. If any of the HTML you write is invalid, Word will not raise an error. Word will write as much of the HTML as it can and will omit any invalid data.
    Office Open XML ("Open XML")The specified the XML is written.
    + * + * For Excel, the specified data is written to the binding as follows: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringThe specified text is inserted as the value of the first bound cell.You can also specify a valid formula to add that formula to the bound cell. For example, setting data to `"=SUM(A1:A5)"` will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Binding.getDataAsync method on the bound cell to read its data, the method can return only the data displayed in the cell (the formula's result).
    An array of arrays ("matrix"), and the shape exactly matches the shape of the binding specifiedThe set of rows and columns are written.You can also specify an array of arrays that contain valid formulas to add them to the bound cells. For example, setting data to `[["=SUM(A1:A5)","=AVERAGE(A1:A5)"]]` will add those two formulas to a binding that contains two cells. Just as when setting a formula on a single bound cell, you can't read the added formulas (or any pre-existing formulas) from the binding with the `Binding.getDataAsync` method - it returns only the data displayed in the bound cells.
    An {@link Office.TableData} object, and the shape of the table matches the bound table.The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".
    + * + * For Excel Online: + * + * - The total number of cells in the value passed to the data parameter can't exceed 20,000 in a single call to this method. + * + * - The number of formatting groups passed to the cellFormat parameter can't exceed 100. + * A single formatting group consists of a set of formatting applied to a specified range of cells. + * + * In all other cases, an error is returned. + * + * The setDataAsync method will write data in a subset of a table or matrix binding if the optional startRow and startColumn parameters are + * specified, and they specify a valid range. + * + * In the callback function passed to the setDataAsync method, you can use the properties of the AsyncResult object to return the following + * information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * @param data The data to be set in the current selection. Possible data types by host: + * + * string: Excel, Excel Online, Word, and Word Online only + * + * array of arrays: Excel and Word only + * + * {@link Office.TableData}: Access, Excel, and Word only + * + * HTML: Word and Word Online only + * + * Office Open XML: Word only + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setDataAsync(data: TableData | any, callback?: (result: AsyncResult) => void): void; } @@ -2601,6 +2860,50 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the specified named item. */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, options?: AddBindingFromNamedItemOptions, callback?: (result: AsyncResult) => void): void; + /** + * Creates a binding against a named object in the document. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * For Excel, the itemName parameter can refer to a named range or a table. + * + * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. + * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. + * + * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * the table in this format: "Sheet1!Table1" + * + * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other + * than the Rich Text content control). + * + * By default, a content control has no Title value assigned. To assign a meaningful name in the Word UI, after inserting a Rich Text content + * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content + * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. + * + * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * @param itemName Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." + * @param bindingType The {@link Office.BindingType} for the data. The method returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the specified named item. + */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding by prompting the user to make a selection on the document. @@ -2633,6 +2936,35 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromPromptAsync(bindingType: BindingType, options?: AddBindingFromPromptOptions, callback?: (result: AsyncResult) => void): void; + /** + * Create a binding by prompting the user to make a selection on the document. + * + * @remarks + *
    Requirement SetsNot in a set
    + * + * Adds a binding object of the specified type to the Bindings collection, which will be identified with the supplied id. + * The method fails if the specified selection cannot be bound. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    + * + * @param bindingType Specifies the type of the binding object to create. Required. + * Returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the selection specified by the user. + */ addFromPromptAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding based on the user's current selection. @@ -2670,6 +3002,40 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromSelectionAsync(bindingType: BindingType, options?: AddBindingFromSelectionOptions, callback?: (result: AsyncResult) => void): void; + /** + * Create a binding based on the user's current selection. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * Adds the specified type of binding object to the Bindings collection, which will be identified with the supplied id. + * + * Note In Excel, if you call the addFromSelectionAsync method passing in the Binding.id of an existing binding, the Binding.type of that + * binding is used, and its type cannot be changed by specifying a different value for the bindingType parameter. + * If you need to use an existing id and change the bindingType, call the Bindings.releaseByIdAsync method first to release the binding, and + * then call the addFromSelectionAsync method to reestablish the binding with a new type. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param bindingType Specifies the type of the binding object to create. Required. + * Returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the selection specified by the user. + */ addFromSelectionAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Gets all bindings that were previously created. @@ -2698,6 +3064,31 @@ declare namespace Office { * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. */ getAllAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets all bindings that were previously created. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. + */ getAllAsync(callback?: (result: AsyncResult) => void): void; /** * Retrieves a binding based on its Name @@ -2727,8 +3118,36 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the Binding object specified by the id in the call. - */ + */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Retrieves a binding based on its Name + * + * @remarks + *
    Requirement SetsCustomXmlParts, MatrixBindings, TableBindings, TextBindings
    + * + * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param id Specifies the unique name of the binding object. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object specified by the id in the call. + */ getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Removes the binding from the document @@ -2759,6 +3178,33 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ releaseByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes the binding from the document + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param id Specifies the unique name to be used to identify the binding object. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ releaseByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; } /** @@ -2815,6 +3261,16 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the nodes associated with the XPath expression. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param xPath The XPath expression that specifies the nodes to get. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. + */ getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Gets the node value. @@ -2827,6 +3283,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the value of the referenced node. */ getNodeValueAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the node value. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the value of the referenced node. + */ getNodeValueAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the text of an XML node in a custom XML part. @@ -2839,6 +3304,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the inner text of the referenced nodes. */ getTextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the text of an XML node in a custom XML part. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the inner text of the referenced nodes. + */ getTextAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the node's XML. @@ -2851,6 +3325,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced node. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the node's XML. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the XML of the referenced node. + */ getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Sets the node value. @@ -2863,6 +3346,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setNodeValueAsync(value: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the node value. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param value The value to be set on the node + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setNodeValueAsync(value: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously sets the text of an XML node in a custom XML part. @@ -2877,6 +3369,17 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setTextAsync(text: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously sets the text of an XML node in a custom XML part. + * + * @remarks + * + * + *
    HostsWord
    Requirement SetsCustomXmlParts
    + * + * @param text Required. The text value of the XML node. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setTextAsync(text: string, callback?: (result: AsyncResult) => void): void; /** * Sets the node XML. @@ -2889,6 +3392,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setXmlAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the node XML. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param xml The XML to be set on the node + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setXmlAsync(xml: string, callback?: (result: AsyncResult) => void): void; } /** @@ -2924,7 +3436,6 @@ declare namespace Office { * Gets the set of namespace prefix mappings ({@link Office.CustomXmlPrefixMappings}) used against the current CustomXmlPart. */ namespaceManager: CustomXmlPrefixMappings; - /** * Adds an event handler to the object using the specified event type. * @@ -2940,45 +3451,68 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler to the object using the specified event type. + * + * @remarks + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType Specifies the type of event to add. For a CustomXmlPart object, the eventType parameter can be specified as + * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.NodeDeletedEventArgs}, + * {@link Office.NodeInsertedEventArgs}, or {@link Office.NodeReplacedEventArgs} + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, callback?: (result: AsyncResult) => void): void; /** * Deletes the Custom XML Part. * - * @remarks - * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Deletes the Custom XML Part. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ deleteAsync(callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. * - * @remarks - * * @param xPath An XPath expression that specifies the nodes you want returned. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. - */ + */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. + * + * @param xPath An XPath expression that specifies the nodes you want returned. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. + */ getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the XML inside this custom XML part. * - * @remarks - * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. - */ + */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the XML inside this custom XML part. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. + */ getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * - * @remarks - * * @param eventType Specifies the type of event to remove. For a CustomXmlPart object, the eventType parameter can be specified as * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. * @param handler The name of the handler to remove. @@ -2986,6 +3520,14 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the specified event type. + * + * @param eventType Specifies the type of event to remove. For a CustomXmlPart object, the eventType parameter can be specified as + * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. + * @param handler The name of the handler to remove. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, callback?: (result: AsyncResult) => void): void; } @@ -3126,6 +3668,13 @@ declare namespace Office { * The `value` property of the result is the newly created CustomXmlPart object. */ addAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously adds a new custom XML part to a file. + * + * @param xml The XML to add to the newly created custom XML part. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the newly created CustomXmlPart object. + */ addAsync(xml: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part by its id. @@ -3137,6 +3686,14 @@ declare namespace Office { * If there is no custom XML part with the specified id, the method returns null. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the specified custom XML part by its id. + * + * @param id The GUID of the custom XML part, including opening and closing braces. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a CustomXmlPart object that represents the specified custom XML part. + * If there is no custom XML part with the specified id, the method returns null. + */ getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part(s) by its namespace. @@ -3147,6 +3704,13 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. */ getByNamespaceAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the specified custom XML part(s) by its namespace. + * + * @param ns The namespace URI. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. + */ getByNamespaceAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** @@ -3183,6 +3747,16 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addNamespaceAsync(prefix: string, ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously adds a prefix to namespace mapping to use when querying an item. + * + * @remarks + * If no namespace is assigned to the requested prefix, the method returns an empty string (""). + * + * @param prefix Specifies the prefix to add to the prefix mapping list. Required. + * @param ns Specifies the namespace URI to assign to the newly added prefix. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addNamespaceAsync(prefix: string, ns: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the namespace mapped to the specified prefix. @@ -3198,6 +3772,18 @@ declare namespace Office { * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. */ getNamespaceAsync(prefix: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the namespace mapped to the specified prefix. + * + * @remarks + * + * If the prefix already exists in the namespace manager, this method will overwrite the mapping of that prefix except when the prefix is one + * added or used by the data store internally, in which case it will return an error. + * + * @param prefix TSpecifies the prefix to get the namespace for. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. + */ getNamespaceAsync(prefix: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the prefix for the specified namespace. @@ -3211,8 +3797,20 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is a string that contains the prefix of the specified namespace. - */ + */ getPrefixAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the prefix for the specified namespace. + * + * @remarks + * + * If no prefix is assigned to the requested namespace, the method returns an empty string (""). If there are multiple prefixes specified in + * the namespace manager, the method returns the first prefix that matches the supplied namespace. + * + * @param ns Specifies the namespace to get the prefix for. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the prefix of the specified namespace. + */ getPrefixAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** @@ -3369,6 +3967,37 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler for a Document object event. + * + * @remarks + *
    Requirement SetsDocumentEvents
    + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    OneNote Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param eventType For a Document object event, the eventType parameter can be specified as `Office.EventType.Document.SelectionChanged` or + * `Office.EventType.Document.ActiveViewChanged`, or the corresponding text value of this enumeration. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.DocumentSelectionChangedEventArgs}. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Returns the state of the current view of the presentation (edit or read). @@ -3397,8 +4026,35 @@ declare namespace Office { * The `value` property of the result is the state of the presentation's current view. * The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides, * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. - */ + */ getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void; + /** + * Returns the state of the current view of the presentation (edit or read). + * + * @remarks + *
    Requirement SetsActiveView
    + * + * Can trigger an event when the view changes. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    PowerPoint Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the state of the presentation's current view. + * The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides, + * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. + */ getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void; /** * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). @@ -3444,6 +4100,48 @@ declare namespace Office { * The `value` property of the result is the File object. */ getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult) => void): void; + /** + * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). + * Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure. + * + * @remarks + *
    Requirement SetsFile
    + * + * For add-ins running in Office host applications other than Office for iOS, the getFileAsync method supports getting files in slices of up + * to 4194304 bytes (4 MB). For add-ins running in Office for iOS apps, the getFileAsync method supports getting files in slices of up to + * 65536 (64 KB). + * + * The fileType parameter can be specified by using the {@link Office.FileType} enumeration or text values. But the possible values vary with + * the host: + * + * Excel for Windows desktop, iPad, and Excel Online: `Office.FileType.Compressed` + * + * Excel for Mac: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * + * PowerPoint for Windows desktop, Mac, iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * + * Word for Windows desktop, Mac, iPad, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param fileType The format in which the file will be returned + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the File object. + */ getFileAsync(fileType: FileType, callback?: (result: AsyncResult) => void): void; /** * Gets file properties of the current document. @@ -3472,8 +4170,35 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). - */ + */ getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets file properties of the current document. + * + * @remarks + *
    Requirement SetsNot in a set
    + * + * You get the file's URL with the url property `asyncResult.value.url`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). + */ getFilePropertiesAsync(callback?: (result: AsyncResult) => void): void; /** * Reads the data contained in the current selection in the document. @@ -3571,6 +4296,98 @@ declare namespace Office { * (See Remarks for more information about data coercion.) */ getSelectedDataAsync(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Reads the data contained in the current selection in the document. + * + * @remarks + *
    Requirement SetsSelection
    + * + * In the callback function that is passed to the getSelectedDataAsync method, you can use the properties of the AsyncResult object to return + * the following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * The possible values for the {@link Office.CoercionType} parameter vary by the host. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    HostSupported coercionType
    Excel, PowerPoint, Project, and Word`Office.CoercionType.Text` (string)
    Excel and Word`Office.CoercionType.Matrix` (array of arrays)
    Access, Excel, and Word`Office.CoercionType.Table` (TableData object)
    Word`Office.CoercionType.Html`
    Word`Office.CoercionType.Ooxml` (Office Open XML)
    PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
    Excel, PowerPoint, and Word`Office.CoercionType.XmlSvg`
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the data in the current selection. + * This is returned in the data structure or format you specified with the coercionType parameter. + * (See Remarks for more information about data coercion.) + */ getSelectedDataAsync(coercionType: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. @@ -3614,6 +4431,46 @@ declare namespace Office { * The `value` property of the result is the current view. */ goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult) => void): void; + /** + * Goes to the specified object or location in the document. + * + * @remarks + *
    Requirement Setsnot in a set
    + * + * PowerPoint doesn't support the goToByIdAsync method in Master Views. + * + * The behavior caused by the selectionMode option varies by host: + * + * In Excel: `Office.SelectionMode.Selected` selects all content in the binding, or named item. Office.SelectionMode.None for text bindings, + * selects the cell; for matrix bindings, table bindings, and named items, selects the first data cell (not first cell in header row for tables). + * + * In PowerPoint: `Office.SelectionMode.Selected` selects the slide title or first textbox on the slide. + * `Office.SelectionMode.None` doesn't select anything. + * + * In Word: `Office.SelectionMode.Selected` selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor + * to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables). + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y
    + * + * @param id The identifier of the object or location to go to. + * @param goToType The type of the location to go to. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the current view. + */ goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. @@ -3644,6 +4501,33 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the specified event type. + * + * @remarks + *
    Requirement SetsDocumentEvents
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    OneNote Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param eventType The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes the specified data into the current selection. @@ -3762,6 +4646,121 @@ declare namespace Office { * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. */ setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Writes the specified data into the current selection. + * + * @remarks + *
    Requirement SetsSelection
    + * + * **Application-specific behaviors** + * + * The following application-specific actions apply when writing data to a selection. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
    If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
    If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).
    If `data` is Office Open XML, the specified XML is inserted.
    If `data` is a base64 encoded image stream, the specified image is inserted.
    If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
    Insert imagesInserted images are placed inline. The imageLeft and imageTop parameters are ignored. The image aspect ratio is always locked. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    ExcelIf a single cell is selectedIf `data` is a string, the specified text is inserted as the value of the current cell.
    If `data` is an array of arrays ("matrix"), the specified set of rows and columns are inserted, if no other data in surrounding cells will be overwritten.
    If `data` is a TableData object, a new Excel table with the specified set of rows and headers is inserted, if no other data in surrounding cells will be overwritten.
    If multiple cells are selectedIf the shape does not match the shape of `data`, an error is returned.
    If the shape of the selection exactly matches the shape of `data`, the values of the selected cells are updated based on the values in `data`.
    Insert imagesInserted images are floating. The position imageLeft and imageTop parameters are relative to currently selected cell(s). Negative imageLeft and imageTop values are allowed and possibly readjusted by Excel to position the image inside a worksheet. Image aspect ratio is locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    All other casesAn error is returned.
    Excel OnlineIn addition to the behaviors described for Excel above, these limits apply when writing data in Excel OnlineThe total number of cells you can write to a worksheet with the `data` parameter can't exceed 20,000 in a single call to this method.
    The number of formatting groups passed to the `cellFormat` parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.
    PowerPointInsert imageInserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    + * + * The possible values for the {@link Office.CoercionType} parameter vary by the host. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    HostSupported coercionType
    Excel, PowerPoint, Project, and Word`Office.CoercionType.Text` (string)
    Excel and Word`Office.CoercionType.Matrix` (array of arrays)
    Access, Excel, and Word`Office.CoercionType.Table` (TableData object)
    Word`Office.CoercionType.Html`
    Word`Office.CoercionType.Ooxml` (Office Open XML)
    PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
    Excel, PowerPoint, and Word`Office.CoercionType.XmlSvg`
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. + * + * If the value passed for `data` is: + * + * - A string: Plain text or anything that can be coerced to a string will be inserted. + * In Excel, you can also specify data as a valid formula to add that formula to the selected cell. For example, setting data to "=SUM(A1:A5)" + * will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added + * formula (or any pre-existing formula) from the bound cell. If you call the Document.getSelectedDataAsync method on the selected cell to + * read its data, the method can return only the data displayed in the cell (the formula's result). + * + * - An array of arrays ("matrix"): Tabular data without headers will be inserted. For example, to write data to three rows in two columns, + * you can pass an array like this: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. To write a single column of three rows, pass an + * array like this: [["R1C1"], ["R2C1"], ["R3C1"]] + * + * In Excel, you can also specify data as an array of arrays that contains valid formulas to add them to the selected cells. For example if no + * other data will be overwritten, setting data to [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] will add those two formulas to the selection. Just as + * when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been + * set - you can only read the formulas' results. + * + * - A TableData object: A table with headers will be inserted. + * In Excel, if you specify formulas in the TableData object you pass for the data parameter, you might not get the results you expect due to + * the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to + * write `data` that contains formulas to a selected table, try specifying the data as an array of arrays (instead of a TableData object), and + * specify the coercionType as Microsoft.Office.Matrix or "matrix". + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. + */ setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get Project field (Ex. ProjectWebAccessURL). @@ -3787,6 +4786,28 @@ declare namespace Office { * */ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get Project field (Ex. ProjectWebAccessURL). + * @param fieldId Project level fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the `fieldValue` property, which represents the value of the specified field. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) @@ -3813,6 +4834,29 @@ declare namespace Office { * */ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) + * @param resourceId Either a string or value of the Resource Id. + * @param fieldId Resource Fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Resource's Id. @@ -3837,6 +4881,27 @@ declare namespace Office { * */ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Resource's Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedResourceAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Task's Id. @@ -3861,6 +4926,27 @@ declare namespace Office { * */ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Task's Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedTaskAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. @@ -3887,6 +4973,29 @@ declare namespace Office { * */ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `viewName` - The name of the view, as a ProjectViewTypes constant. + * `viewType` - The type of view, as the integer value of a ProjectViewTypes constant. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedViewAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. @@ -3915,6 +5024,31 @@ declare namespace Office { * */ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. + * @param taskId Either a string or value of the Task Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `taskName` - The name of the task. + * `wssTaskId` - The ID of the task in the synchronized SharePoint task list. If the project is not synchronized with a SharePoint task list, the value is 0. + * `resourceNames` - The comma-separated list of the names of resources that are assigned to the task. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskAsync(taskId: string, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get task field for provided task Id. (Ex. StartDate). @@ -3941,6 +5075,29 @@ declare namespace Office { * */ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get task field for provided task Id. (Ex. StartDate). + * @param taskId Either a string or value of the Task Id. + * @param fieldId Task Fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the `fieldValue` property, which represents the value of the specified field. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. @@ -3967,6 +5124,29 @@ declare namespace Office { * */ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `listName` - the name of the synchronized SharePoint task list. + * `serverUrl` - the URL of the synchronized SharePoint task list. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getWSSUrlAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of resources in the current project. @@ -3994,6 +5174,30 @@ declare namespace Office { * */ getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the maximum index of the collection of resources in the current project. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the highest index number in the current project's resource collection. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getMaxResourceIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of tasks in the current project. @@ -4021,6 +5225,30 @@ declare namespace Office { * */ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the maximum index of the collection of tasks in the current project. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the highest index number in the current project's task collection. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getMaxTaskIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. @@ -4049,6 +5277,31 @@ declare namespace Office { * */ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param resourceIndex The index of the resource in the collection of resources for the project. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. @@ -4077,6 +5330,31 @@ declare namespace Office { * */ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the GUID of the task that has the specified index in the task collection. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param taskIndex The index of the task in the collection of tasks for the project. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the task as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set resource field for specified resource Id. @@ -4106,6 +5384,32 @@ declare namespace Office { * */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Set resource field for specified resource Id. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param resourceId Either a string or value of the Resource Id. + * @param fieldId Resource Fields. + * @param fieldValue Value of the target field. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set task field for specified task Id. @@ -4135,6 +5439,32 @@ declare namespace Office { * */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Set task field for specified task Id. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param taskId Either a string or value of the Task Id. + * @param fieldId Task Fields. + * @param fieldValue Value of the target field. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; } /** @@ -4386,6 +5716,61 @@ declare namespace Office { * */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler for the settingsChanged event. + * + * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the + * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. + * + * @remarks + * + *
    Requirement SetsSettings
    + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType Specifies the type of event to add. Required. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.SettingsChangedEventArgs}. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no data or object to retrieve when adding an event handler.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad
    Access Y
    Excel Y
    + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Retrieves the specified setting. @@ -4542,6 +5927,40 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the settingsChanged event. + * + * @remarks + * + *
    Requirement SetsSettings
    + * + * If the optional handler parameter is omitted when calling the removeHandlerAsync method, all event handlers for the specified eventType + * will be removed. + * + * When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback + * function's only parameter. + * + * In the callback function passed to the removeHandlerAsync method, you can use the properties of the AsyncResult object to return the + * following information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad
    Access Y
    Excel Y
    + * + * @param eventType Specifies the type of event to remove. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Persists the in-memory copy of the settings property bag in the document. @@ -4600,6 +6019,61 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ saveAsync(options?: SaveSettingsOptions, callback?: (result: AsyncResult) => void): void; + /** + * Persists the in-memory copy of the settings property bag in the document. + * + * @remarks + * Any settings previously saved by an add-in are loaded when it is initialized, so during the lifetime of the session you can just use the + * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are + * available the next time the add-in is used, use the saveAsync method. + * + * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful + * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to + * all instances. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ saveAsync(callback?: (result: AsyncResult) => void): void; /** * Sets or creates the specified setting. @@ -4861,6 +6335,47 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addColumnsAsync(tableData: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified data to the table as additional columns. + * + * @remarks + * + * To add one or more columns specifying the values of the data and headers, pass a TableData object as the data parameter. To add one or more + * columns specifying only the data, pass an array of arrays ("matrix") as the data parameter. + * + * The success or failure of an addColumnsAsync operation is atomic. That is, the entire add columns operation must succeed, or it will be + * completely rolled back (and the AsyncResult.status property returned to the callback will report failure): + * + * - Each row in the array you pass as the data argument must have the same number of rows as the table being updated. If not, the entire + * operation will fail. + * + * - Each row and cell in the array must successfully add that row or cell to the table in the newly added column(s). If any row or cell + * fails to be set for any reason, the entire operation will fail. + * + * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. + * + * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in + * a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param tableData An array of arrays ("matrix") or a TableData object that contains one or more columns of data to add to the table. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addColumnsAsync(tableData: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Adds the specified data to the table as additional rows. @@ -4902,6 +6417,44 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addRowsAsync(rows: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified data to the table as additional rows. + * + * @remarks + * + * The success or failure of an addRowsAsync operation is atomic. That is, the entire add columns operation must succeed, or it will be + * completely rolled back (and the AsyncResult.status property returned to the callback will report failure): + * + * - Each row in the array you pass as the data argument must have the same number of columns as the table being updated. If not, the entire + * operation will fail. + * + * - Each column and cell in the array must successfully add that column or cell to the table in the newly added rows(s). If any column or + * cell fails to be set for any reason, the entire operation will fail. + * + * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. + * + * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in + * a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param rows An array of arrays ("matrix") or a TableData object that contains one or more rows of data to add to the table. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addRowsAsync(rows: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. @@ -4930,6 +6483,31 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAllDataValuesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. + * + * @remarks + * + * In Excel, if the table has no header row, this method will delete the table itself. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ deleteAllDataValuesAsync(callback?: (result: AsyncResult) => void): void; /** * Clears formatting on the bound table. @@ -4955,6 +6533,28 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ clearFormatsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Clears formatting on the bound table. + * + * @remarks + * See {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | Format tables in add-ins for Excel} for more information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ clearFormatsAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the formatting on specified items in the table. @@ -5010,6 +6610,58 @@ declare namespace Office { * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. */ getFormatsAsync(cellReference?: any, formats?: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; + /** + * Gets the formatting on specified items in the table. + * + * @remarks + * + * **Returned format structure** + * + * Each JavaScript object in the return value array has this form: `{cells:{ cell_range }, format:{ format_definition }}` + * + * The `cells:` property specifies the range you want format using one of the following values: + * + * **Supported ranges in cells property** + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    cells range settingsDescription
    `{row: n}`Specifies the range that is the zero-based nth row of data in the table.
    `{column: n}`Specifies the range that is the zero-based nth column of data in the table.
    `{row: i, column: j}`Specifies the single cell that is the ith row and jth column of the table.
    `Office.Table.All`Specifies the entire table, including column headers, data, and totals (if any).
    `Office.Table.Data`Specifies only the data in the table (no headers and totals).
    `Office.Table.Headers`Specifies only the header row.
    + * + * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel + * (Right-click \> Format Cells or Home \> Format \> Format Cells). + * + * @param cellReference An object literal containing name-value pairs that specify the range of cells to get formatting from. + * @param formats An array specifying the format properties to get. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. + */ getFormatsAsync(cellReference?: any, formats?: any[], callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; /** * Sets formatting on specified items and data in the table. @@ -5124,6 +6776,117 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setFormatsAsync(cellFormat: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets formatting on specified items and data in the table. + * + * @remarks + * + * **Specifying the cellFormat parameter** + * + * Use the cellFormat parameter to set or change cell formatting values, such as width, height, font, background, alignment, and so on. + * The value you pass as the cellFormat parameter is an array that contains a list of one or more JavaScript objects that specify which cells + * to target (`cells:`) and the formats (`format:`) to apply to them. + * + * Each JavaScript object in the cellFormat array has this form: `{cells:{ cell_range }, format:{ format_definition }}` + * + * The `cells:` property specifies the range you want format using one of the following values: + * + * **Supported ranges in cells property** + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    cells range settingsDescription
    `{row: n}`Specifies the range that is the zero-based nth row of data in the table.
    `{column: n}`Specifies the range that is the zero-based nth column of data in the table.
    `{row: i, column: j}`Specifies the single cell that is the ith row and jth column of the table.
    `Office.Table.All`Specifies the entire table, including column headers, data, and totals (if any).
    `Office.Table.Data`Specifies only the data in the table (no headers and totals).
    `Office.Table.Headers`Specifies only the header row.
    + * + * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel + * (Right-click \> Format Cells or Home \> Format \> Format Cells). + * + * You specify the value of the `format:` property as a list of one or more property name - value pairs in a JavaScript object literal. The + * property name specifies the name of the formatting property to set, and value specifies the property value. + * You can specify multiple values for a given format, such as both a font's color and size. + * + * Here's three `format:` property value examples: + * + * `//Set cells: font color to green and size to 15 points.` + * + * `format: {fontColor : "green", fontSize : 15}` + * + * `//Set cells: border to dotted blue.` + * + * `format: {borderStyle: "dotted", borderColor: "blue"}` + * + * `//Set cells: background to red and alignment to centered.` + * + * `format: {backgroundColor: "red", alignHorizontal: "center"}` + * + * + * You can specify number formats by specifying the number formatting "code" string in the `numberFormat:` property. + * The number format strings you can specify correspond to those you can set in Excel using the Custom category on the Number tab of the Format Cells dialog box. + * This example shows how to format a number as a percentage with two decimal places: + * + * `format: {numberFormat:"0.00%"}` + * + * For more detail, see how to {@link https://support.office.com/article/create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 | Create a custom number format}. + * + * To set formatting on tables when writing data, use the tableOptions and cellFormat optional parameters of the + * `Document.setSelectedDataAsync` or `TableBinding.setDataAsync` methods. + * + * Setting formatting with the optional parameters of the `Document.setSelectedDataAsync` and `TableBinding.setDataAsync` methods only works + * to set formatting when writing data the first time. + * To make formatting changes after writing data, use the following methods: + * + * - To update cell formatting, such as font color and style, use the `TableBinding.setFormatsAsync` method (this method). + * + * - To update table options, such as banded rows and filter buttons, use the `TableBinding.setTableOptions` method. + * + * - To clear formatting, use the `TableBinding.clearFormats` method. + * + * For more details and examples, see + * {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | How to format tables in add-ins for Excel}. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param cellFormat An array that contains one or more JavaScript objects that specify which cells to target and the formatting to apply to them. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setFormatsAsync(cellFormat: any[], callback?: (result: AsyncResult) => void): void; /** * Updates table formatting options on the bound table. @@ -5178,6 +6941,57 @@ declare namespace Office { * */ setTableOptionsAsync(tableOptions: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Updates table formatting options on the bound table. + * + * @remarks + * + * + *
    HostsExcel
    Requirement SetsNot in a set
    + * + * In the callback function passed to the goToByIdAsync method, you can use the properties of the AsyncResult object to return the following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no data or object to retrieve when setting formats.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param tableOptions An object literal containing a list of property name-value pairs that define the table options to apply. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + */ setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index f0fee147ba..bea8c12db6 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1093,6 +1093,104 @@ declare namespace Office { * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. */ displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + /** + * Displays a dialog to show or collect information from the user or to facilitate Web navigation. + * + * @remarks + * + * + *
    HostsWord, Excel, Outlook, PowerPoint
    Requirement setsDialogApi, Mailbox 1.4
    + * + * This method is available in the DialogApi requirement set for Word, Excel, or PowerPoint add-ins, and in the Mailbox requirement set 1.4 + * for Outlook. For more on how to specify a requirement set in your manifest, see + * {@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements | Specify Office hosts and API requirements}. + * + * The initial page must be on the same domain as the parent page (the startAddress parameter). After the initial page loads, you can go to + * other domains. + * + * Any page calling `office.context.ui.messageParent` must also be on the same domain as the parent page. + * + * **Design considerations**: + * + * The following design considerations apply to dialog boxes: + * + * - An Office Add-in task pane can have only one dialog box open at any time. Multiple dialogs can be open at the same time from Add-in + * Commands (custom ribbon buttons or menu items). + * + * - Every dialog box can be moved and resized by the user. + * + * - Every dialog box is centered on the screen when opened. + * + * - Dialog boxes appear on top of the host application and in the order in which they were created. + * + * Use a dialog box to: + * + * - Display authentication pages to collect user credentials. + * + * - Display an error/progress/input screen from a ShowTaskpane or ExecuteAction command. + * + * - Temporarily increase the surface area that a user has available to complete a task. + * + * Do not use a dialog box to interact with a document. Use a task pane instead. + * + * For a design pattern that you can use to create a dialog box, see + * {@link https://github.com/OfficeDev/Office-Add-in-UX-Design-Patterns/blob/master/Patterns/Client_Dialog.md | Client Dialog} in the Office + * Add-in UX Design Patterns repository on GitHub. + * + * **displayDialogAsync Errors**: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Code numberMeaning
    12004The domain of the URL passed to displayDialogAsync is not trusted. The domain must be either the same domain as the host page (including protocol and port number), or it must be registered in the section of the add-in manifest.
    12005The URL passed to displayDialogAsync uses the HTTP protocol. HTTPS is required. (In some versions of Office, the error message returned with 12005 is the same one returned for 12004.)
    12007A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time.
    12009The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog.
    + * + * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the + * following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to
    AsyncResult.valueAccess the Dialog object.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextAccess your user-defined object or value, if you passed one as the asyncContext parameter.
    + * + * @param startAddress - Accepts the initial HTTPS URL that opens in the dialog. + * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. + */ displayDialogAsync(startAddress: string, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. @@ -2291,6 +2389,17 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + /** + * Adds an event handler to the object for the specified {@link Office.EventType}. Supported EventTypes are + * `Office.EventType.BindingDataChanged` and `Office.EventType.BindingSelectionChanged`. + * + * @remarks + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.BindingDataChangedEventArgs} or {@link Office.BindingSelectionChangedEventArgs}. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => void): void; /** * Returns the data contained within the binding. @@ -2307,6 +2416,19 @@ declare namespace Office { * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. */ getDataAsync(options?: GetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Returns the data contained within the binding. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * When called from a MatrixBinding or TableBinding, the getDataAsync method will return a subset of the bound values if the optional startRow, + * startColumn, rowCount, and columnCount parameters are specified (and they specify a contiguous and valid range). + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the values in the specified binding. + * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. + */ getDataAsync(callback?: (result: AsyncResult) => void): void; /** * Removes the specified handler from the binding for the specified event type. @@ -2319,6 +2441,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes the specified handler from the binding for the specified event type. + * + * @remarks + *
    Requirement SetsBindingEvents
    + * + * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes data to the bound section of the document represented by the specified binding object. @@ -2451,6 +2582,134 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Writes data to the bound section of the document represented by the specified binding object. + * + * @remarks + * + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * The value passed for data contains the data to be written in the binding. The kind of value passed determines what will be written as + * described in the following table. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringPlain text or anything that can be coerced to a string will be written.
    An array of arrays ("matrix")Tabular data without headers will be written. For example, to write data to three rows in two columns, you can pass an array like this: `[["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]`. To write a single column of three rows, pass an array like this: `[["R1C1"], ["R2C1"], ["R3C1"]]`.
    An {@link Office.TableData} objectA table with headers will be written.
    + * + * Additionally, these application-specific actions apply when writing data to a binding. For Word, the specified data is written to the + * binding as follows: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringThe specified text is written.
    An array of arrays ("matrix") or an {@link Office.TableData} objectA Word table is written.
    HTMLThe specified HTML is written. If any of the HTML you write is invalid, Word will not raise an error. Word will write as much of the HTML as it can and will omit any invalid data.
    Office Open XML ("Open XML")The specified the XML is written.
    + * + * For Excel, the specified data is written to the binding as follows: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    `data` valueData written
    A stringThe specified text is inserted as the value of the first bound cell.You can also specify a valid formula to add that formula to the bound cell. For example, setting data to `"=SUM(A1:A5)"` will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Binding.getDataAsync method on the bound cell to read its data, the method can return only the data displayed in the cell (the formula's result).
    An array of arrays ("matrix"), and the shape exactly matches the shape of the binding specifiedThe set of rows and columns are written.You can also specify an array of arrays that contain valid formulas to add them to the bound cells. For example, setting data to `[["=SUM(A1:A5)","=AVERAGE(A1:A5)"]]` will add those two formulas to a binding that contains two cells. Just as when setting a formula on a single bound cell, you can't read the added formulas (or any pre-existing formulas) from the binding with the `Binding.getDataAsync` method - it returns only the data displayed in the bound cells.
    An {@link Office.TableData} object, and the shape of the table matches the bound table.The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".
    + * + * For Excel Online: + * + * - The total number of cells in the value passed to the data parameter can't exceed 20,000 in a single call to this method. + * + * - The number of formatting groups passed to the cellFormat parameter can't exceed 100. + * A single formatting group consists of a set of formatting applied to a specified range of cells. + * + * In all other cases, an error is returned. + * + * The setDataAsync method will write data in a subset of a table or matrix binding if the optional startRow and startColumn parameters are + * specified, and they specify a valid range. + * + * In the callback function passed to the setDataAsync method, you can use the properties of the AsyncResult object to return the following + * information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * @param data The data to be set in the current selection. Possible data types by host: + * + * string: Excel, Excel Online, Word, and Word Online only + * + * array of arrays: Excel and Word only + * + * {@link Office.TableData}: Access, Excel, and Word only + * + * HTML: Word and Word Online only + * + * Office Open XML: Word only + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setDataAsync(data: TableData | any, callback?: (result: AsyncResult) => void): void; } @@ -2601,6 +2860,50 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the specified named item. */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, options?: AddBindingFromNamedItemOptions, callback?: (result: AsyncResult) => void): void; + /** + * Creates a binding against a named object in the document. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * For Excel, the itemName parameter can refer to a named range or a table. + * + * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. + * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. + * + * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * the table in this format: "Sheet1!Table1" + * + * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other + * than the Rich Text content control). + * + * By default, a content control has no Title value assigned. To assign a meaningful name in the Word UI, after inserting a Rich Text content + * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content + * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. + * + * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * @param itemName Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." + * @param bindingType The {@link Office.BindingType} for the data. The method returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the specified named item. + */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding by prompting the user to make a selection on the document. @@ -2633,6 +2936,35 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromPromptAsync(bindingType: BindingType, options?: AddBindingFromPromptOptions, callback?: (result: AsyncResult) => void): void; + /** + * Create a binding by prompting the user to make a selection on the document. + * + * @remarks + *
    Requirement SetsNot in a set
    + * + * Adds a binding object of the specified type to the Bindings collection, which will be identified with the supplied id. + * The method fails if the specified selection cannot be bound. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    + * + * @param bindingType Specifies the type of the binding object to create. Required. + * Returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the selection specified by the user. + */ addFromPromptAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding based on the user's current selection. @@ -2670,6 +3002,40 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromSelectionAsync(bindingType: BindingType, options?: AddBindingFromSelectionOptions, callback?: (result: AsyncResult) => void): void; + /** + * Create a binding based on the user's current selection. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * Adds the specified type of binding object to the Bindings collection, which will be identified with the supplied id. + * + * Note In Excel, if you call the addFromSelectionAsync method passing in the Binding.id of an existing binding, the Binding.type of that + * binding is used, and its type cannot be changed by specifying a different value for the bindingType parameter. + * If you need to use an existing id and change the bindingType, call the Bindings.releaseByIdAsync method first to release the binding, and + * then call the addFromSelectionAsync method to reestablish the binding with a new type. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param bindingType Specifies the type of the binding object to create. Required. + * Returns null if the selected object cannot be coerced into the specified type. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object that represents the selection specified by the user. + */ addFromSelectionAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Gets all bindings that were previously created. @@ -2698,6 +3064,31 @@ declare namespace Office { * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. */ getAllAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets all bindings that were previously created. + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. + */ getAllAsync(callback?: (result: AsyncResult) => void): void; /** * Retrieves a binding based on its Name @@ -2727,8 +3118,36 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the Binding object specified by the id in the call. - */ + */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Retrieves a binding based on its Name + * + * @remarks + *
    Requirement SetsCustomXmlParts, MatrixBindings, TableBindings, TextBindings
    + * + * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param id Specifies the unique name of the binding object. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the Binding object specified by the id in the call. + */ getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Removes the binding from the document @@ -2759,6 +3178,33 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ releaseByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes the binding from the document + * + * @remarks + *
    Requirement SetsMatrixBindings, TableBindings, TextBindings
    + * + * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param id Specifies the unique name to be used to identify the binding object. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ releaseByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; } /** @@ -2815,6 +3261,16 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the nodes associated with the XPath expression. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param xPath The XPath expression that specifies the nodes to get. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. + */ getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Gets the node value. @@ -2827,6 +3283,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the value of the referenced node. */ getNodeValueAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the node value. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the value of the referenced node. + */ getNodeValueAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the text of an XML node in a custom XML part. @@ -2839,6 +3304,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the inner text of the referenced nodes. */ getTextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the text of an XML node in a custom XML part. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the inner text of the referenced nodes. + */ getTextAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the node's XML. @@ -2851,6 +3325,15 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced node. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets the node's XML. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the XML of the referenced node. + */ getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Sets the node value. @@ -2863,6 +3346,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setNodeValueAsync(value: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the node value. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param value The value to be set on the node + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setNodeValueAsync(value: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously sets the text of an XML node in a custom XML part. @@ -2877,6 +3369,17 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setTextAsync(text: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously sets the text of an XML node in a custom XML part. + * + * @remarks + * + * + *
    HostsWord
    Requirement SetsCustomXmlParts
    + * + * @param text Required. The text value of the XML node. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setTextAsync(text: string, callback?: (result: AsyncResult) => void): void; /** * Sets the node XML. @@ -2889,6 +3392,15 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setXmlAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the node XML. + * + * @remarks + *
    Requirement SetsCustomXmlParts
    + * + * @param xml The XML to be set on the node + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setXmlAsync(xml: string, callback?: (result: AsyncResult) => void): void; } /** @@ -2924,7 +3436,6 @@ declare namespace Office { * Gets the set of namespace prefix mappings ({@link Office.CustomXmlPrefixMappings}) used against the current CustomXmlPart. */ namespaceManager: CustomXmlPrefixMappings; - /** * Adds an event handler to the object using the specified event type. * @@ -2940,45 +3451,68 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler to the object using the specified event type. + * + * @remarks + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType Specifies the type of event to add. For a CustomXmlPart object, the eventType parameter can be specified as + * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.NodeDeletedEventArgs}, + * {@link Office.NodeInsertedEventArgs}, or {@link Office.NodeReplacedEventArgs} + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, callback?: (result: AsyncResult) => void): void; /** * Deletes the Custom XML Part. * - * @remarks - * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Deletes the Custom XML Part. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ deleteAsync(callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. * - * @remarks - * * @param xPath An XPath expression that specifies the nodes you want returned. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. - */ + */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. + * + * @param xPath An XPath expression that specifies the nodes you want returned. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. + */ getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the XML inside this custom XML part. * - * @remarks - * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. - */ + */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the XML inside this custom XML part. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. + */ getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * - * @remarks - * * @param eventType Specifies the type of event to remove. For a CustomXmlPart object, the eventType parameter can be specified as * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. * @param handler The name of the handler to remove. @@ -2986,6 +3520,14 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the specified event type. + * + * @param eventType Specifies the type of event to remove. For a CustomXmlPart object, the eventType parameter can be specified as + * `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. + * @param handler The name of the handler to remove. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, callback?: (result: AsyncResult) => void): void; } @@ -3126,6 +3668,13 @@ declare namespace Office { * The `value` property of the result is the newly created CustomXmlPart object. */ addAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously adds a new custom XML part to a file. + * + * @param xml The XML to add to the newly created custom XML part. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the newly created CustomXmlPart object. + */ addAsync(xml: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part by its id. @@ -3137,6 +3686,14 @@ declare namespace Office { * If there is no custom XML part with the specified id, the method returns null. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the specified custom XML part by its id. + * + * @param id The GUID of the custom XML part, including opening and closing braces. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a CustomXmlPart object that represents the specified custom XML part. + * If there is no custom XML part with the specified id, the method returns null. + */ getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part(s) by its namespace. @@ -3147,6 +3704,13 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. */ getByNamespaceAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the specified custom XML part(s) by its namespace. + * + * @param ns The namespace URI. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. + */ getByNamespaceAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** @@ -3183,6 +3747,16 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addNamespaceAsync(prefix: string, ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously adds a prefix to namespace mapping to use when querying an item. + * + * @remarks + * If no namespace is assigned to the requested prefix, the method returns an empty string (""). + * + * @param prefix Specifies the prefix to add to the prefix mapping list. Required. + * @param ns Specifies the namespace URI to assign to the newly added prefix. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addNamespaceAsync(prefix: string, ns: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the namespace mapped to the specified prefix. @@ -3198,6 +3772,18 @@ declare namespace Office { * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. */ getNamespaceAsync(prefix: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the namespace mapped to the specified prefix. + * + * @remarks + * + * If the prefix already exists in the namespace manager, this method will overwrite the mapping of that prefix except when the prefix is one + * added or used by the data store internally, in which case it will return an error. + * + * @param prefix TSpecifies the prefix to get the namespace for. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. + */ getNamespaceAsync(prefix: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the prefix for the specified namespace. @@ -3211,8 +3797,20 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is a string that contains the prefix of the specified namespace. - */ + */ getPrefixAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously gets the prefix for the specified namespace. + * + * @remarks + * + * If no prefix is assigned to the requested namespace, the method returns an empty string (""). If there are multiple prefixes specified in + * the namespace manager, the method returns the first prefix that matches the supplied namespace. + * + * @param ns Specifies the namespace to get the prefix for. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is a string that contains the prefix of the specified namespace. + */ getPrefixAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** @@ -3369,6 +3967,37 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler for a Document object event. + * + * @remarks + *
    Requirement SetsDocumentEvents
    + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    OneNote Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param eventType For a Document object event, the eventType parameter can be specified as `Office.EventType.Document.SelectionChanged` or + * `Office.EventType.Document.ActiveViewChanged`, or the corresponding text value of this enumeration. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.DocumentSelectionChangedEventArgs}. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Returns the state of the current view of the presentation (edit or read). @@ -3397,8 +4026,35 @@ declare namespace Office { * The `value` property of the result is the state of the presentation's current view. * The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides, * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. - */ + */ getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void; + /** + * Returns the state of the current view of the presentation (edit or read). + * + * @remarks + *
    Requirement SetsActiveView
    + * + * Can trigger an event when the view changes. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    PowerPoint Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the state of the presentation's current view. + * The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides, + * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. + */ getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void; /** * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). @@ -3444,6 +4100,48 @@ declare namespace Office { * The `value` property of the result is the File object. */ getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult) => void): void; + /** + * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). + * Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure. + * + * @remarks + *
    Requirement SetsFile
    + * + * For add-ins running in Office host applications other than Office for iOS, the getFileAsync method supports getting files in slices of up + * to 4194304 bytes (4 MB). For add-ins running in Office for iOS apps, the getFileAsync method supports getting files in slices of up to + * 65536 (64 KB). + * + * The fileType parameter can be specified by using the {@link Office.FileType} enumeration or text values. But the possible values vary with + * the host: + * + * Excel for Windows desktop, iPad, and Excel Online: `Office.FileType.Compressed` + * + * Excel for Mac: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * + * PowerPoint for Windows desktop, Mac, iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * + * Word for Windows desktop, Mac, iPad, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param fileType The format in which the file will be returned + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the File object. + */ getFileAsync(fileType: FileType, callback?: (result: AsyncResult) => void): void; /** * Gets file properties of the current document. @@ -3472,8 +4170,35 @@ declare namespace Office { * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). - */ + */ getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Gets file properties of the current document. + * + * @remarks + *
    Requirement SetsNot in a set
    + * + * You get the file's URL with the url property `asyncResult.value.url`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). + */ getFilePropertiesAsync(callback?: (result: AsyncResult) => void): void; /** * Reads the data contained in the current selection in the document. @@ -3571,6 +4296,98 @@ declare namespace Office { * (See Remarks for more information about data coercion.) */ getSelectedDataAsync(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Reads the data contained in the current selection in the document. + * + * @remarks + *
    Requirement SetsSelection
    + * + * In the callback function that is passed to the getSelectedDataAsync method, you can use the properties of the AsyncResult object to return + * the following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * The possible values for the {@link Office.CoercionType} parameter vary by the host. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    HostSupported coercionType
    Excel, PowerPoint, Project, and Word`Office.CoercionType.Text` (string)
    Excel and Word`Office.CoercionType.Matrix` (array of arrays)
    Access, Excel, and Word`Office.CoercionType.Table` (TableData object)
    Word`Office.CoercionType.Html`
    Word`Office.CoercionType.Ooxml` (Office Open XML)
    PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
    Excel, PowerPoint, and Word`Office.CoercionType.XmlSvg`
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the data in the current selection. + * This is returned in the data structure or format you specified with the coercionType parameter. + * (See Remarks for more information about data coercion.) + */ getSelectedDataAsync(coercionType: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. @@ -3614,6 +4431,46 @@ declare namespace Office { * The `value` property of the result is the current view. */ goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult) => void): void; + /** + * Goes to the specified object or location in the document. + * + * @remarks + *
    Requirement Setsnot in a set
    + * + * PowerPoint doesn't support the goToByIdAsync method in Master Views. + * + * The behavior caused by the selectionMode option varies by host: + * + * In Excel: `Office.SelectionMode.Selected` selects all content in the binding, or named item. Office.SelectionMode.None for text bindings, + * selects the cell; for matrix bindings, table bindings, and named items, selects the first data cell (not first cell in header row for tables). + * + * In PowerPoint: `Office.SelectionMode.Selected` selects the slide title or first textbox on the slide. + * `Office.SelectionMode.None` doesn't select anything. + * + * In Word: `Office.SelectionMode.Selected` selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor + * to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables). + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y
    + * + * @param id The identifier of the object or location to go to. + * @param goToType The type of the location to go to. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the current view. + */ goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. @@ -3644,6 +4501,33 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the specified event type. + * + * @remarks + *
    Requirement SetsDocumentEvents
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    OneNote Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param eventType The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes the specified data into the current selection. @@ -3762,6 +4646,121 @@ declare namespace Office { * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. */ setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Writes the specified data into the current selection. + * + * @remarks + *
    Requirement SetsSelection
    + * + * **Application-specific behaviors** + * + * The following application-specific actions apply when writing data to a selection. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
    If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
    If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).
    If `data` is Office Open XML, the specified XML is inserted.
    If `data` is a base64 encoded image stream, the specified image is inserted.
    If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
    Insert imagesInserted images are placed inline. The imageLeft and imageTop parameters are ignored. The image aspect ratio is always locked. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    ExcelIf a single cell is selectedIf `data` is a string, the specified text is inserted as the value of the current cell.
    If `data` is an array of arrays ("matrix"), the specified set of rows and columns are inserted, if no other data in surrounding cells will be overwritten.
    If `data` is a TableData object, a new Excel table with the specified set of rows and headers is inserted, if no other data in surrounding cells will be overwritten.
    If multiple cells are selectedIf the shape does not match the shape of `data`, an error is returned.
    If the shape of the selection exactly matches the shape of `data`, the values of the selected cells are updated based on the values in `data`.
    Insert imagesInserted images are floating. The position imageLeft and imageTop parameters are relative to currently selected cell(s). Negative imageLeft and imageTop values are allowed and possibly readjusted by Excel to position the image inside a worksheet. Image aspect ratio is locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    All other casesAn error is returned.
    Excel OnlineIn addition to the behaviors described for Excel above, these limits apply when writing data in Excel OnlineThe total number of cells you can write to a worksheet with the `data` parameter can't exceed 20,000 in a single call to this method.
    The number of formatting groups passed to the `cellFormat` parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.
    PowerPointInsert imageInserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
    + * + * The possible values for the {@link Office.CoercionType} parameter vary by the host. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    HostSupported coercionType
    Excel, PowerPoint, Project, and Word`Office.CoercionType.Text` (string)
    Excel and Word`Office.CoercionType.Matrix` (array of arrays)
    Access, Excel, and Word`Office.CoercionType.Table` (TableData object)
    Word`Office.CoercionType.Html`
    Word`Office.CoercionType.Ooxml` (Office Open XML)
    PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
    Excel, PowerPoint, and Word`Office.CoercionType.XmlSvg`
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Project Y
    Word Y Y Y Y
    + * + * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. + * + * If the value passed for `data` is: + * + * - A string: Plain text or anything that can be coerced to a string will be inserted. + * In Excel, you can also specify data as a valid formula to add that formula to the selected cell. For example, setting data to "=SUM(A1:A5)" + * will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added + * formula (or any pre-existing formula) from the bound cell. If you call the Document.getSelectedDataAsync method on the selected cell to + * read its data, the method can return only the data displayed in the cell (the formula's result). + * + * - An array of arrays ("matrix"): Tabular data without headers will be inserted. For example, to write data to three rows in two columns, + * you can pass an array like this: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. To write a single column of three rows, pass an + * array like this: [["R1C1"], ["R2C1"], ["R3C1"]] + * + * In Excel, you can also specify data as an array of arrays that contains valid formulas to add them to the selected cells. For example if no + * other data will be overwritten, setting data to [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] will add those two formulas to the selection. Just as + * when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been + * set - you can only read the formulas' results. + * + * - A TableData object: A table with headers will be inserted. + * In Excel, if you specify formulas in the TableData object you pass for the data parameter, you might not get the results you expect due to + * the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to + * write `data` that contains formulas to a selected table, try specifying the data as an array of arrays (instead of a TableData object), and + * specify the coercionType as Microsoft.Office.Matrix or "matrix". + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. + */ setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get Project field (Ex. ProjectWebAccessURL). @@ -3787,6 +4786,28 @@ declare namespace Office { * */ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get Project field (Ex. ProjectWebAccessURL). + * @param fieldId Project level fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the `fieldValue` property, which represents the value of the specified field. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) @@ -3813,6 +4834,29 @@ declare namespace Office { * */ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) + * @param resourceId Either a string or value of the Resource Id. + * @param fieldId Resource Fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Resource's Id. @@ -3837,6 +4881,27 @@ declare namespace Office { * */ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Resource's Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedResourceAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Task's Id. @@ -3861,6 +4926,27 @@ declare namespace Office { * */ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Task's Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedTaskAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. @@ -3887,6 +4973,29 @@ declare namespace Office { * */ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `viewName` - The name of the view, as a ProjectViewTypes constant. + * `viewType` - The type of view, as the integer value of a ProjectViewTypes constant. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getSelectedViewAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. @@ -3915,6 +5024,31 @@ declare namespace Office { * */ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. + * @param taskId Either a string or value of the Task Id. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `taskName` - The name of the task. + * `wssTaskId` - The ID of the task in the synchronized SharePoint task list. If the project is not synchronized with a SharePoint task list, the value is 0. + * `resourceNames` - The comma-separated list of the names of resources that are assigned to the task. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskAsync(taskId: string, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get task field for provided task Id. (Ex. StartDate). @@ -3941,6 +5075,29 @@ declare namespace Office { * */ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get task field for provided task Id. (Ex. StartDate). + * @param taskId Either a string or value of the Task Id. + * @param fieldId Task Fields. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the `fieldValue` property, which represents the value of the specified field. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. @@ -3967,6 +5124,29 @@ declare namespace Office { * */ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result contains the following properties: + * `listName` - the name of the synchronized SharePoint task list. + * `serverUrl` - the URL of the synchronized SharePoint task list. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getWSSUrlAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of resources in the current project. @@ -3994,6 +5174,30 @@ declare namespace Office { * */ getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the maximum index of the collection of resources in the current project. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the highest index number in the current project's resource collection. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getMaxResourceIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of tasks in the current project. @@ -4021,6 +5225,30 @@ declare namespace Office { * */ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the maximum index of the collection of tasks in the current project. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the highest index number in the current project's task collection. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getMaxTaskIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. @@ -4049,6 +5277,31 @@ declare namespace Office { * */ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param resourceIndex The index of the resource in the collection of resources for the project. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the resource as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. @@ -4077,6 +5330,31 @@ declare namespace Office { * */ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the GUID of the task that has the specified index in the task collection. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param taskIndex The index of the task in the collection of tasks for the project. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is the GUID of the task as a string. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set resource field for specified resource Id. @@ -4106,6 +5384,32 @@ declare namespace Office { * */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Set resource field for specified resource Id. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param resourceId Either a string or value of the Resource Id. + * @param fieldId Resource Fields. + * @param fieldValue Value of the target field. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set task field for specified task Id. @@ -4135,6 +5439,32 @@ declare namespace Office { * */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Set task field for specified task Id. + * + * Important: This API works only in Project 2016 on Windows desktop. + * + * @param taskId Either a string or value of the Task Id. + * @param fieldId Task Fields. + * @param fieldValue Value of the target field. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser)
    Project Y
    + */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; } /** @@ -4386,6 +5716,61 @@ declare namespace Office { * */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an event handler for the settingsChanged event. + * + * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the + * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. + * + * @remarks + * + *
    Requirement SetsSettings
    + * + * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * @param eventType Specifies the type of event to add. Required. + * @param handler The event handler function to add, whose only parameter is of type {@link Office.SettingsChangedEventArgs}. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no data or object to retrieve when adding an event handler.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad
    Access Y
    Excel Y
    + */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Retrieves the specified setting. @@ -4542,6 +5927,40 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an event handler for the settingsChanged event. + * + * @remarks + * + *
    Requirement SetsSettings
    + * + * If the optional handler parameter is omitted when calling the removeHandlerAsync method, all event handlers for the specified eventType + * will be removed. + * + * When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback + * function's only parameter. + * + * In the callback function passed to the removeHandlerAsync method, you can use the properties of the AsyncResult object to return the + * following information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad
    Access Y
    Excel Y
    + * + * @param eventType Specifies the type of event to remove. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Persists the in-memory copy of the settings property bag in the document. @@ -4600,6 +6019,61 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ saveAsync(options?: SaveSettingsOptions, callback?: (result: AsyncResult) => void): void; + /** + * Persists the in-memory copy of the settings property bag in the document. + * + * @remarks + * Any settings previously saved by an add-in are loaded when it is initialized, so during the lifetime of the session you can just use the + * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are + * available the next time the add-in is used, use the saveAsync method. + * + * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful + * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to + * all instances. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no object or data to retrieve.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    PowerPoint Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ saveAsync(callback?: (result: AsyncResult) => void): void; /** * Sets or creates the specified setting. @@ -4861,6 +6335,47 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addColumnsAsync(tableData: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified data to the table as additional columns. + * + * @remarks + * + * To add one or more columns specifying the values of the data and headers, pass a TableData object as the data parameter. To add one or more + * columns specifying only the data, pass an array of arrays ("matrix") as the data parameter. + * + * The success or failure of an addColumnsAsync operation is atomic. That is, the entire add columns operation must succeed, or it will be + * completely rolled back (and the AsyncResult.status property returned to the callback will report failure): + * + * - Each row in the array you pass as the data argument must have the same number of rows as the table being updated. If not, the entire + * operation will fail. + * + * - Each row and cell in the array must successfully add that row or cell to the table in the newly added column(s). If any row or cell + * fails to be set for any reason, the entire operation will fail. + * + * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. + * + * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in + * a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param tableData An array of arrays ("matrix") or a TableData object that contains one or more columns of data to add to the table. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addColumnsAsync(tableData: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Adds the specified data to the table as additional rows. @@ -4902,6 +6417,44 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addRowsAsync(rows: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified data to the table as additional rows. + * + * @remarks + * + * The success or failure of an addRowsAsync operation is atomic. That is, the entire add columns operation must succeed, or it will be + * completely rolled back (and the AsyncResult.status property returned to the callback will report failure): + * + * - Each row in the array you pass as the data argument must have the same number of columns as the table being updated. If not, the entire + * operation will fail. + * + * - Each column and cell in the array must successfully add that column or cell to the table in the newly added rows(s). If any column or + * cell fails to be set for any reason, the entire operation will fail. + * + * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. + * + * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in + * a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param rows An array of arrays ("matrix") or a TableData object that contains one or more rows of data to add to the table. Required. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ addRowsAsync(rows: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. @@ -4930,6 +6483,31 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAllDataValuesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. + * + * @remarks + * + * In Excel, if the table has no header row, this method will delete the table itself. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Access Y
    Excel Y Y Y Y
    Word Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ deleteAllDataValuesAsync(callback?: (result: AsyncResult) => void): void; /** * Clears formatting on the bound table. @@ -4955,6 +6533,28 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ clearFormatsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Clears formatting on the bound table. + * + * @remarks + * See {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | Format tables in add-ins for Excel} for more information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ clearFormatsAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the formatting on specified items in the table. @@ -5010,6 +6610,58 @@ declare namespace Office { * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. */ getFormatsAsync(cellReference?: any, formats?: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; + /** + * Gets the formatting on specified items in the table. + * + * @remarks + * + * **Returned format structure** + * + * Each JavaScript object in the return value array has this form: `{cells:{ cell_range }, format:{ format_definition }}` + * + * The `cells:` property specifies the range you want format using one of the following values: + * + * **Supported ranges in cells property** + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    cells range settingsDescription
    `{row: n}`Specifies the range that is the zero-based nth row of data in the table.
    `{column: n}`Specifies the range that is the zero-based nth column of data in the table.
    `{row: i, column: j}`Specifies the single cell that is the ith row and jth column of the table.
    `Office.Table.All`Specifies the entire table, including column headers, data, and totals (if any).
    `Office.Table.Data`Specifies only the data in the table (no headers and totals).
    `Office.Table.Headers`Specifies only the header row.
    + * + * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel + * (Right-click \> Format Cells or Home \> Format \> Format Cells). + * + * @param cellReference An object literal containing name-value pairs that specify the range of cells to get formatting from. + * @param formats An array specifying the format properties to get. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. + */ getFormatsAsync(cellReference?: any, formats?: any[], callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; /** * Sets formatting on specified items and data in the table. @@ -5124,6 +6776,117 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setFormatsAsync(cellFormat: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets formatting on specified items and data in the table. + * + * @remarks + * + * **Specifying the cellFormat parameter** + * + * Use the cellFormat parameter to set or change cell formatting values, such as width, height, font, background, alignment, and so on. + * The value you pass as the cellFormat parameter is an array that contains a list of one or more JavaScript objects that specify which cells + * to target (`cells:`) and the formats (`format:`) to apply to them. + * + * Each JavaScript object in the cellFormat array has this form: `{cells:{ cell_range }, format:{ format_definition }}` + * + * The `cells:` property specifies the range you want format using one of the following values: + * + * **Supported ranges in cells property** + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    cells range settingsDescription
    `{row: n}`Specifies the range that is the zero-based nth row of data in the table.
    `{column: n}`Specifies the range that is the zero-based nth column of data in the table.
    `{row: i, column: j}`Specifies the single cell that is the ith row and jth column of the table.
    `Office.Table.All`Specifies the entire table, including column headers, data, and totals (if any).
    `Office.Table.Data`Specifies only the data in the table (no headers and totals).
    `Office.Table.Headers`Specifies only the header row.
    + * + * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel + * (Right-click \> Format Cells or Home \> Format \> Format Cells). + * + * You specify the value of the `format:` property as a list of one or more property name - value pairs in a JavaScript object literal. The + * property name specifies the name of the formatting property to set, and value specifies the property value. + * You can specify multiple values for a given format, such as both a font's color and size. + * + * Here's three `format:` property value examples: + * + * `//Set cells: font color to green and size to 15 points.` + * + * `format: {fontColor : "green", fontSize : 15}` + * + * `//Set cells: border to dotted blue.` + * + * `format: {borderStyle: "dotted", borderColor: "blue"}` + * + * `//Set cells: background to red and alignment to centered.` + * + * `format: {backgroundColor: "red", alignHorizontal: "center"}` + * + * + * You can specify number formats by specifying the number formatting "code" string in the `numberFormat:` property. + * The number format strings you can specify correspond to those you can set in Excel using the Custom category on the Number tab of the Format Cells dialog box. + * This example shows how to format a number as a percentage with two decimal places: + * + * `format: {numberFormat:"0.00%"}` + * + * For more detail, see how to {@link https://support.office.com/article/create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 | Create a custom number format}. + * + * To set formatting on tables when writing data, use the tableOptions and cellFormat optional parameters of the + * `Document.setSelectedDataAsync` or `TableBinding.setDataAsync` methods. + * + * Setting formatting with the optional parameters of the `Document.setSelectedDataAsync` and `TableBinding.setDataAsync` methods only works + * to set formatting when writing data the first time. + * To make formatting changes after writing data, use the following methods: + * + * - To update cell formatting, such as font color and style, use the `TableBinding.setFormatsAsync` method (this method). + * + * - To update table options, such as banded rows and filter buttons, use the `TableBinding.setTableOptions` method. + * + * - To clear formatting, use the `TableBinding.clearFormats` method. + * + * For more details and examples, see + * {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | How to format tables in add-ins for Excel}. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param cellFormat An array that contains one or more JavaScript objects that specify which cells to target and the formatting to apply to them. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + */ setFormatsAsync(cellFormat: any[], callback?: (result: AsyncResult) => void): void; /** * Updates table formatting options on the bound table. @@ -5178,6 +6941,57 @@ declare namespace Office { * */ setTableOptionsAsync(tableOptions: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Updates table formatting options on the bound table. + * + * @remarks + * + * + *
    HostsExcel
    Requirement SetsNot in a set
    + * + * In the callback function passed to the goToByIdAsync method, you can use the properties of the AsyncResult object to return the following information. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    PropertyUse to...
    AsyncResult.valueAlways returns undefined because there is no data or object to retrieve when setting formats.
    AsyncResult.statusDetermine the success or failure of the operation.
    AsyncResult.errorAccess an Error object that provides error information if the operation failed.
    AsyncResult.asyncContextA user-defined item of any type that is returned in the AsyncResult object without being altered.
    + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
    Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
    Excel Y Y Y Y
    + * + * @param tableOptions An object literal containing a list of property name-value pairs that define the table options to apply. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. + * + */ setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** From d17c85404fd1e7821b2eb9f6207b1059ae783b66 Mon Sep 17 00:00:00 2001 From: licui Date: Wed, 30 Jan 2019 16:51:41 -0500 Subject: [PATCH 229/312] Add missing API functions in System --- types/openfin/index.d.ts | 24 +++++++++++++++++------- types/openfin/openfin-tests.ts | 12 +++++++++++- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 5d2cd28742..a47a68d48f 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -47,6 +47,7 @@ declare namespace fin { type ClearCacheOption = import('./_v2/api/system/clearCacheOption').ClearCacheOption; type CookieInfo = import('./_v2/api/system/cookie').CookieInfo; type CookieOption = import('./_v2/api/system/cookie').CookieOption; + type CrashReporterOption = import('./_v2/api/system/crashReporterOption').CrashReporterOption; type AppAssetInfo = import('./_v2/api/system/download-asset').AppAssetInfo; type AppAssetRequest = import('./_v2/api/system/download-asset').AppAssetRequest; type RuntimeDownloadOptions = import('./_v2/api/system/download-asset').RuntimeDownloadOptions; @@ -581,14 +582,18 @@ declare namespace fin { * Returns information about the app asset. */ getAppAssetInfo(options: AppAssetRequest, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + */ + getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void; /** * Get additional info of cookies. */ getCookies(option: CookieOption, callback?: (info: CookieInfo[]) => void, errorCallback?: (reason: string) => void): void; /** - * Retrieves the command line argument string that started OpenFin Runtime. + * Get the current state of the crash reporter. */ - getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void; + getCrashReporterState(callback?: (state: CrashReporterOption) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves the configuration object that started the OpenFin Runtime. */ @@ -621,6 +626,10 @@ declare namespace fin { * Retrieves an array containing information for each log file. */ getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns a unique identifier (UUID) provided by the machine. + */ + getMachineId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves the minimum (inclusive) logging level that is currently being written to the logs. */ @@ -710,6 +719,12 @@ declare namespace fin { * Shows the Chrome Developer Tools for the specified window. */ showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Start the crash reporter for the browser process if not already running. + * You can optionally specify `diagnosticMode` to have the logs sent to + * OpenFin on runtime close + */ + startCrashReporter(options: CrashReporterOption, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds. */ @@ -719,11 +734,6 @@ declare namespace fin { killTree: boolean, callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, errorCallback?: (reason: string) => void): void; - terminateExternalProcess( - processUuid: string, - timeout: number, - callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, - errorCallback?: (reason: string) => void): void; /** * Update the OpenFin Runtime Proxy settings. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index d1b8ebe32d..7fcfcef23d 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -395,6 +395,8 @@ function test_system() { const cookie1 = cookies[0]; console.log(cookie1.name, cookie1.domain, cookie1.path); }, err => console.log(err)); + // getCrashReporterState + fin.desktop.System.getCrashReporterState(state => console.log(state), err => console.error(err)); // getDeviceId fin.desktop.System.getDeviceId(id => { console.log("The id of the device is: " + id); @@ -429,6 +431,8 @@ function test_system() { console.log(`The filename of the log is ${logInfo.name}, the size is ${logInfo.size}, and the date of creation is ${logInfo.date}`); }); }); + // getMachineId + fin.desktop.System.getMachineId(id => console.log(id), err => console.error(err)); // getMinLogLevel fin.desktop.System.getMinLogLevel(level => console.log(level), err => console.log(err)); // getMonitorInfo @@ -586,6 +590,12 @@ function test_system() { }, err => { console.log("failure: " + err); }); + // startCrashReporter + fin.desktop.System.startCrashReporter({diagnosticMode: true}, () => { + console.log('success'); + }, err => { + console.log(err); + }); // terminateExternalProcess fin.desktop.System.launchExternalProcess({ // notepad is in the system's PATH @@ -599,7 +609,7 @@ function test_system() { // Attempt to close the process. Terminate after 4 seconds if it // has not done so. - fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, true, info => { console.log("Termination result " + info.result); }, reason => { console.log("failure: " + reason); From 3a2022aac4f2760b536f5f8c06654300161f9a67 Mon Sep 17 00:00:00 2001 From: Drew Wyatt Date: Wed, 30 Jan 2019 16:53:55 -0500 Subject: [PATCH 230/312] indentation --- types/jwplayer/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index f02159bc6f..91f0d455cc 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -266,10 +266,10 @@ declare namespace jwplayer { } interface CastParam { - available: boolean; - active: boolean; - deviceName: string; - type: 'cast'; + available: boolean; + active: boolean; + deviceName: string; + type: 'cast'; } interface EventParams { From 9ed64f112b662ddf6b04ad484d91bef118330b8a Mon Sep 17 00:00:00 2001 From: Gola Date: Wed, 30 Jan 2019 16:05:12 -0700 Subject: [PATCH 231/312] Moved OptionsBase out of namespace to prevent accidental import Added documentation back for returnPromise --- types/clean-css/index.d.ts | 132 ++++++++++++++++++++----------------- 1 file changed, 71 insertions(+), 61 deletions(-) diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index c474741ec8..a033f708a9 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -8,78 +8,78 @@ import { RequestOptions as HttpsRequestOptions } from "https"; import { RequestOptions as HttpRequestOptions } from "http"; -declare namespace CleanCSS { +/** + * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output + */ +interface OptionsBase { /** - * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output + * Controls compatibility mode used; defaults to ie10+ using `'*'`. + * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` */ - interface OptionsBase { - /** - * Controls compatibility mode used; defaults to ie10+ using `'*'`. - * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` - */ - compatibility?: "*" | "ie9" | "ie8" | "ie7" | CompatibilityOptions; + compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions; - /** - * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function - */ - fetch?: (uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void; + /** + * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function + */ + fetch?: (uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void; - /** - * Controls output CSS formatting; defaults to `false`. - * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. - */ - format?: "beautify" | "keep-breaks" | FormatOptions | false; + /** + * Controls output CSS formatting; defaults to `false`. + * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. + */ + format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false; - /** - * inline option whitelists which @import rules will be processed. Defaults to `'local'` - * Accepts the following values: - * 'local': enables local inlining; - * 'remote': enables remote inlining; - * 'none': disables all inlining; - * 'all': enables all inlining, same as ['local', 'remote']; - * '[uri]': enables remote inlining from the specified uri; - * '![url]': disables remote inlining from the specified uri; - */ - inline?: ReadonlyArray | false; + /** + * inline option whitelists which @import rules will be processed. Defaults to `'local'` + * Accepts the following values: + * 'local': enables local inlining; + * 'remote': enables remote inlining; + * 'none': disables all inlining; + * 'all': enables all inlining, same as ['local', 'remote']; + * '[uri]': enables remote inlining from the specified uri; + * '![url]': disables remote inlining from the specified uri; + */ + inline?: ReadonlyArray | false; - /** - * Controls extra options for inlining remote @import rules - */ - inlineRequest?: HttpRequestOptions | HttpsRequestOptions; + /** + * Controls extra options for inlining remote @import rules + */ + inlineRequest?: HttpRequestOptions | HttpsRequestOptions; - /** - * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; - */ - inlineTimeout?: number; + /** + * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; + */ + inlineTimeout?: number; - /** - * Controls optimization level used; defaults to `1`. - * Level hash exposes `1`, and `2`. - */ - level?: 0 | 1 | 2 | OptimizationsOptions; + /** + * Controls optimization level used; defaults to `1`. + * Level hash exposes `1`, and `2`. + */ + level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions; - /** - * Controls URL rebasing; defaults to `true`; - */ - rebase?: boolean; + /** + * Controls URL rebasing; defaults to `true`; + */ + rebase?: boolean; - /** - * controls a directory to which all URLs are rebased, most likely the directory under which the output file - * will live; defaults to the current directory; - */ - rebaseTo?: string; + /** + * controls a directory to which all URLs are rebased, most likely the directory under which the output file + * will live; defaults to the current directory; + */ + rebaseTo?: string; - /** - * Controls whether an output source map is built; defaults to `false` - */ - sourceMap?: boolean; + /** + * Controls whether an output source map is built; defaults to `false` + */ + sourceMap?: boolean; - /** - * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` - */ - sourceMapInlineSources?: boolean; - } + /** + * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` + */ + sourceMapInlineSources?: boolean; +} +declare namespace CleanCSS { /** * Output returned when calling minify functions */ @@ -648,12 +648,22 @@ declare namespace CleanCSS { /** * Options when returning a promise */ - type OptionsPromise = OptionsBase & { returnPromise: true }; + type OptionsPromise = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise: true + }; /** * Options when returning an output */ - type OptionsOutput = OptionsBase & { returnPromise?: false }; + type OptionsOutput = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise?: false + }; /** * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` From 5239b343f6c0e3a36c3cf16e970ed9582e4aba86 Mon Sep 17 00:00:00 2001 From: Gola Date: Wed, 30 Jan 2019 16:08:02 -0700 Subject: [PATCH 232/312] Fixed linting error --- types/clean-css/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index a033f708a9..9f2dfe9358 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -648,7 +648,7 @@ declare namespace CleanCSS { /** * Options when returning a promise */ - type OptionsPromise = OptionsBase & { + type OptionsPromise = OptionsBase & { /** * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` */ @@ -658,7 +658,7 @@ declare namespace CleanCSS { /** * Options when returning an output */ - type OptionsOutput = OptionsBase & { + type OptionsOutput = OptionsBase & { /** * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` */ From 371507cae9f9a0a88a9161a971c8917cf82c358a Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:16:40 -0200 Subject: [PATCH 233/312] added mem-cache module types definitions --- types/mem-cache/index.d.ts | 19 +++++++++++++++++++ types/mem-cache/mem-cache-tests.ts | 17 +++++++++++++++++ types/mem-cache/tsconfig.json | 24 ++++++++++++++++++++++++ types/mem-cache/tslint.json | 1 + 4 files changed, 61 insertions(+) create mode 100644 types/mem-cache/index.d.ts create mode 100644 types/mem-cache/mem-cache-tests.ts create mode 100644 types/mem-cache/tsconfig.json create mode 100644 types/mem-cache/tslint.json diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts new file mode 100644 index 0000000000..2bf77e8c71 --- /dev/null +++ b/types/mem-cache/index.d.ts @@ -0,0 +1,19 @@ +import { EventEmitter } from 'events'; + +export interface ICacheOptions { + timeout?: number; + doesNotRenewTimeout?: boolean; + timeoutDisabled?: boolean; +} + +export default class Cache extends EventEmitter { + public keys: string[]; + public length: number; + + constructor(options?: number | ICacheOptions); + + public set(key: string, value: any, timeout?: number): void; + public get(key: string): any; + public remove(key: string): void; + public clean(): void; +} diff --git a/types/mem-cache/mem-cache-tests.ts b/types/mem-cache/mem-cache-tests.ts new file mode 100644 index 0000000000..420c72f200 --- /dev/null +++ b/types/mem-cache/mem-cache-tests.ts @@ -0,0 +1,17 @@ +import Cache from 'mem-cache'; + +const cache = new Cache(); // $ExpectType Cache +const cache2 = new Cache(100000); // $ExpectType Cache +const cache3 = new Cache({ + doesNotRenewTimeout: true, + timeout: 100000, + timeoutDisabled: false +}); // $ExpectType Cache + +cache.set('foo', 'bar'); // $ExpectType void +cache.get('foo'); // $ExpectType any +cache.remove('foo'); // $ExpectType void +cache.clean(); // $ExpectType void +cache.length; // $ExpectType number +cache.keys; // $ExpectType string[] + diff --git a/types/mem-cache/tsconfig.json b/types/mem-cache/tsconfig.json new file mode 100644 index 0000000000..9587e02f72 --- /dev/null +++ b/types/mem-cache/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mem-cache-tests.ts" + ], + "baseUrl": "types", + "typeRoots": ["types"] +} diff --git a/types/mem-cache/tslint.json b/types/mem-cache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mem-cache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5b1ff713aca7c870592e385feba014813fe1cad1 Mon Sep 17 00:00:00 2001 From: markdreyer Date: Wed, 30 Jan 2019 17:29:31 -0600 Subject: [PATCH 234/312] Update ParseConfig.dynamicTyping definition From documentation https://www.papaparse.com/docs#config : It also accepts an object or a function. If object it's values should be a boolean to indicate if dynamic typing should be applied for each column number (or header name if using headers). If it's a function, it should return a boolean value for each field number (or name if using headers) which will be passed as first argument. --- types/papaparse/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index fc97ef210c..df09dde329 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -97,7 +97,7 @@ export interface ParseConfig { quoteChar?: string; // default: '"' header?: boolean; // default: false trimHeaders?: boolean; // default: false - dynamicTyping?: boolean; // default: false + dynamicTyping?: boolean | { [key: string]: boolean; [index: number]: boolean;} | ((field: string) => boolean); // default: false preview?: number; // default: 0 encoding?: string; // default: "" worker?: boolean; // default: false From 0b462231d669795ef8f2daecb4be5e7a09f362de Mon Sep 17 00:00:00 2001 From: markdreyer Date: Wed, 30 Jan 2019 17:33:53 -0600 Subject: [PATCH 235/312] Update type variable names to match documentation --- types/papaparse/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index df09dde329..300e33b4a5 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -97,7 +97,7 @@ export interface ParseConfig { quoteChar?: string; // default: '"' header?: boolean; // default: false trimHeaders?: boolean; // default: false - dynamicTyping?: boolean | { [key: string]: boolean; [index: number]: boolean;} | ((field: string) => boolean); // default: false + dynamicTyping?: boolean | { [headerName: string]: boolean; [columnNumber: number]: boolean;} | ((field: string | number) => boolean); // default: false preview?: number; // default: 0 encoding?: string; // default: "" worker?: boolean; // default: false From 5693cd23c5cd66decd6cd0cf6fb91ba2b15042c8 Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:35:48 -0200 Subject: [PATCH 236/312] added mem-cache module types definitions --- types/mem-cache/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts index 2bf77e8c71..fbee520d33 100644 --- a/types/mem-cache/index.d.ts +++ b/types/mem-cache/index.d.ts @@ -1,3 +1,8 @@ +// Type definitions for mem-cache v0.0.5 +// Project: https://github.com/silviom/node-mem-cache +// Definitions by: Pedro Mutter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + import { EventEmitter } from 'events'; export interface ICacheOptions { From b4e374267e2edb79e92199c898e656df37dddbfd Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:38:19 -0200 Subject: [PATCH 237/312] added mem-cache module types definitions --- types/mem-cache/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/mem-cache/tsconfig.json b/types/mem-cache/tsconfig.json index 9587e02f72..3c3a2e701a 100644 --- a/types/mem-cache/tsconfig.json +++ b/types/mem-cache/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 53b75eb119358ad3b774117298c993ec90735333 Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:44:01 -0200 Subject: [PATCH 238/312] fix test requirements errors --- types/mem-cache/index.d.ts | 18 +++++++++--------- types/mem-cache/mem-cache-tests.ts | 1 - 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts index fbee520d33..e4adf69f0e 100644 --- a/types/mem-cache/index.d.ts +++ b/types/mem-cache/index.d.ts @@ -1,24 +1,24 @@ -// Type definitions for mem-cache v0.0.5 +// Type definitions for mem-cache v0.1.0 // Project: https://github.com/silviom/node-mem-cache // Definitions by: Pedro Mutter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { EventEmitter } from 'events'; -export interface ICacheOptions { +export interface CacheOptions { timeout?: number; doesNotRenewTimeout?: boolean; timeoutDisabled?: boolean; } export default class Cache extends EventEmitter { - public keys: string[]; - public length: number; + keys: string[]; + length: number; - constructor(options?: number | ICacheOptions); + constructor(options?: number | CacheOptions); - public set(key: string, value: any, timeout?: number): void; - public get(key: string): any; - public remove(key: string): void; - public clean(): void; + set(key: string, value: any, timeout?: number): void; + get(key: string): any; + remove(key: string): void; + clean(): void; } diff --git a/types/mem-cache/mem-cache-tests.ts b/types/mem-cache/mem-cache-tests.ts index 420c72f200..94232e4410 100644 --- a/types/mem-cache/mem-cache-tests.ts +++ b/types/mem-cache/mem-cache-tests.ts @@ -14,4 +14,3 @@ cache.remove('foo'); // $ExpectType void cache.clean(); // $ExpectType void cache.length; // $ExpectType number cache.keys; // $ExpectType string[] - From ccc18670b0ad0e79ad68ac0e2df914855364fb95 Mon Sep 17 00:00:00 2001 From: Rodrigo Vieira de Alencar Date: Wed, 30 Jan 2019 15:52:20 +1100 Subject: [PATCH 239/312] Update for prosemirror-model 1.7.0 --- types/prosemirror-model/index.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/prosemirror-model/index.d.ts b/types/prosemirror-model/index.d.ts index a86037d0f8..d2d9670584 100644 --- a/types/prosemirror-model/index.d.ts +++ b/types/prosemirror-model/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prosemirror-model 1.5 +// Type definitions for prosemirror-model 1.7 // Project: https://github.com/ProseMirror/prosemirror-model // Definitions by: Bradley Ayers // David Hahn @@ -1240,6 +1240,11 @@ export interface NodeSpec { * parsing rules in your schema. */ parseDOM?: ParseRule[] | null; + /** + * Defines the default way a node of this type should be serialized + * to a string representation for debugging (e.g. in error messages). + */ + toDebugString?: ((node: ProsemirrorNode) => string) | null; } export interface MarkSpec { /** @@ -1272,6 +1277,11 @@ export interface MarkSpec { * The group or space-separated groups to which this mark belongs. */ group?: string | null; + /** + * Determines whether marks of this type can span multiple adjacent + * nodes when serialized to DOM/HTML. Defaults to true. + */ + spanning?: boolean | null; /** * Defines the default way marks of this type should be serialized * to DOM/HTML. From 7dadf2dedd8d48fca48eb870e9f0729f32afd2db Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:48:12 -0200 Subject: [PATCH 240/312] fix test requirements version and wrong expect type --- types/mem-cache/index.d.ts | 2 +- types/mem-cache/mem-cache-tests.ts | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts index e4adf69f0e..3258d6364e 100644 --- a/types/mem-cache/index.d.ts +++ b/types/mem-cache/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mem-cache v0.1.0 +// Type definitions for mem-cache v1.0.0 // Project: https://github.com/silviom/node-mem-cache // Definitions by: Pedro Mutter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/mem-cache/mem-cache-tests.ts b/types/mem-cache/mem-cache-tests.ts index 94232e4410..2b667258d3 100644 --- a/types/mem-cache/mem-cache-tests.ts +++ b/types/mem-cache/mem-cache-tests.ts @@ -1,12 +1,6 @@ import Cache from 'mem-cache'; const cache = new Cache(); // $ExpectType Cache -const cache2 = new Cache(100000); // $ExpectType Cache -const cache3 = new Cache({ - doesNotRenewTimeout: true, - timeout: 100000, - timeoutDisabled: false -}); // $ExpectType Cache cache.set('foo', 'bar'); // $ExpectType void cache.get('foo'); // $ExpectType any From c07384eacc4acd36be2db8eb9790c932a78d2c15 Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Wed, 30 Jan 2019 21:52:49 -0200 Subject: [PATCH 241/312] fix header --- types/mem-cache/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts index 3258d6364e..f5e135a363 100644 --- a/types/mem-cache/index.d.ts +++ b/types/mem-cache/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mem-cache v1.0.0 +// Type definitions for mem-cache 1.0 // Project: https://github.com/silviom/node-mem-cache // Definitions by: Pedro Mutter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From c8cdd4b998b43a1e68d64d2367308458c7b77b7d Mon Sep 17 00:00:00 2001 From: markdreyer Date: Wed, 30 Jan 2019 18:57:01 -0600 Subject: [PATCH 242/312] Add tests for ParseConfig.dynamicTyping --- types/papaparse/papaparse-tests.ts | 58 ++++++++++++++++++------------ 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 50929ff512..a22ea5b14d 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -2,12 +2,12 @@ import Papa = require("papaparse"); import { - ParseConfig, - UnparseConfig, - UnparseObject, - ParseError, - ParseMeta, - ParseResult + ParseConfig, + UnparseConfig, + UnparseObject, + ParseError, + ParseMeta, + ParseResult } from "papaparse"; import { Readable } from "stream"; @@ -19,14 +19,26 @@ var res = Papa.parse("3,3,3"); res.errors[0].code; Papa.parse("3,3,3", { - delimiter: ';', - comments: false, + delimiter: ';', + comments: false, trimHeaders: false, + step: function (results, p) { + p.abort(); + results.data.length; + }, + dynamicTyping: true +}); - step: function (results, p) { - p.abort(); - results.data.length; - } +Papa.parse("3,3,3", { + dynamicTyping: (field: string | number): boolean => /headerName/i.test(field.toString()) +}); + +Papa.parse("3,3,3", { + dynamicTyping: {'headerName': true} +}); + +Papa.parse("3,3,3", { + dynamicTyping: {5: true} }); var file = new File(null, null, null); @@ -35,20 +47,20 @@ Papa.parse(file, { transform: function(value, field) { }, - complete: function (a, b) { - a.meta.fields; - b.name; - } + complete: function (a, b) { + a.meta.fields; + b.name; + } }); const readable = new Readable() const rows = [ - "1,2,3", - "4,5,6" + "1,2,3", + "4,5,6" ] rows.forEach(r => { - readable.push(r); + readable.push(r); }); const papaStream: NodeJS.ReadWriteStream = Papa.parse(Papa.NODE_STREAM_INPUT); @@ -61,16 +73,16 @@ readable.pipe(papaStream); Papa.unparse([{ a: 1, b: 1, c: 1 }]); Papa.unparse([[1, 2, 3], [4, 5, 6]]); Papa.unparse({ - fields: ["3"], - data: [] + fields: ["3"], + data: [] }); Papa.unparse([{ a: 1, b: 1, c: 1 }], { quotes: false }); Papa.unparse([{ a: 1, b: 1, c: 1 }], { quotes: [false, true, true] }); Papa.unparse([[1, 2, 3], [4, 5, 6]], { delimiter: "," }); Papa.unparse({ - fields: ["3"], - data: [] + fields: ["3"], + data: [] }, { newline: "\n" }); From 6471e3065240488bb1ee6e079d64265192a10f7c Mon Sep 17 00:00:00 2001 From: Ming Date: Wed, 30 Jan 2019 17:09:14 -0800 Subject: [PATCH 243/312] mongoose: Fix ConnectionOptionsBase. - Fix type for keepAlive: should be boolean instead of number. - Add optional field keepAliveInitialDelay. - Fix numbers in comment. --- types/mongoose/index.d.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b7d3b5d9c6..47585e20d3 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -16,6 +16,7 @@ // Dan Manastireanu // stablio // Emmanuel Gautier +// Ming Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -316,6 +317,16 @@ declare module "mongoose" { readyState: number; } + /** + * Connection optional settings. + * + * see + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connect + * and + * http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html + * for all available options. + * + */ interface ConnectionOptionsBase { /** database Name for Mongodb Atlas Connection */ dbName?: string; @@ -339,11 +350,13 @@ declare module "mongoose" { poolSize?: number; /** Reconnect on error (default: true) */ autoReconnect?: boolean; - /** TCP KeepAlive on the socket with a X ms delay before start (default: 0). */ - keepAlive?: number; - /** TCP Connection timeout setting (default: 0) */ + /** TCP Connection keep alive enabled (default: true) */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket (default 30000) */ + keepAliveInitialDelay?: number; + /** TCP Connection timeout setting (default: 30000) */ connectTimeoutMS?: number; - /** TCP Socket timeout setting (default: 0) */ + /** TCP Socket timeout setting (default: 360000) */ socketTimeoutMS?: number; /** If the database authentication is dependent on another databaseName. */ authSource?: string; From 392300d5f8726c5b3a50bae8abde0c432377ce3d Mon Sep 17 00:00:00 2001 From: Derek Kniffin Date: Wed, 30 Jan 2019 16:49:53 -0500 Subject: [PATCH 244/312] Added types for axios-case-converter --- .../axios-case-converter-tests.ts | 6 +++++ types/axios-case-converter/index.d.ts | 7 ++++++ types/axios-case-converter/package.json | 6 +++++ types/axios-case-converter/tsconfig.json | 23 +++++++++++++++++++ types/axios-case-converter/tslint.json | 1 + 5 files changed, 43 insertions(+) create mode 100644 types/axios-case-converter/axios-case-converter-tests.ts create mode 100644 types/axios-case-converter/index.d.ts create mode 100644 types/axios-case-converter/package.json create mode 100644 types/axios-case-converter/tsconfig.json create mode 100644 types/axios-case-converter/tslint.json diff --git a/types/axios-case-converter/axios-case-converter-tests.ts b/types/axios-case-converter/axios-case-converter-tests.ts new file mode 100644 index 0000000000..77fa927976 --- /dev/null +++ b/types/axios-case-converter/axios-case-converter-tests.ts @@ -0,0 +1,6 @@ +import axios from "axios"; +import applyConverters from "axios-case-converter"; + +applyConverters(); // $ExpectError + +applyConverters(axios.create()); // $ExpectType AxiosInstance diff --git a/types/axios-case-converter/index.d.ts b/types/axios-case-converter/index.d.ts new file mode 100644 index 0000000000..2071ee4dbc --- /dev/null +++ b/types/axios-case-converter/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for axios-case-converter 0.3 +// Project: https://github.com/mpyw/axios-case-converter +// Definitions by: Derek Kniffin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { AxiosInstance } from "axios"; + +export default function applyConverters(axios: AxiosInstance): AxiosInstance; diff --git a/types/axios-case-converter/package.json b/types/axios-case-converter/package.json new file mode 100644 index 0000000000..ab98e74e0b --- /dev/null +++ b/types/axios-case-converter/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "axios": "^0.16.1" + } +} diff --git a/types/axios-case-converter/tsconfig.json b/types/axios-case-converter/tsconfig.json new file mode 100644 index 0000000000..fb3102b6eb --- /dev/null +++ b/types/axios-case-converter/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", + "axios-case-converter-tests.ts" + ] +} diff --git a/types/axios-case-converter/tslint.json b/types/axios-case-converter/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/axios-case-converter/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f044c380f6be2c942201f6207c11461a946e1856 Mon Sep 17 00:00:00 2001 From: Matt Krick Date: Wed, 30 Jan 2019 18:21:34 -0800 Subject: [PATCH 245/312] add support for getRequest --- types/relay-runtime/index.d.ts | 37 +++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 6589acfd6d..a4b7106c4f 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -42,9 +42,40 @@ export type RelayContainer = any; // ~~~~~~~~~~~~~~~~~~~~~ // File: https://github.com/facebook/relay/blob/fe0e70f10bbcba1fff89911313ea69f24569464b/packages/relay-runtime/util/RelayConcreteNode.js -export type ConcreteFragment = any; -export type ConcreteRequest = any; -export type ConcreteBatchRequest = any; +export interface ConcreteFragment { + kind: string; + name: string; + type: string; + metadata: {[key: string]: any} | null; + argumentDefinitions: any[]; + selections: any[]; +} +export interface ConcreteRequest { + kind: string; + operationKind: string; + name: string; + id: string | null; + text: string | null; + metadata: {[key: string]: any}; + fragment: ConcreteFragment; + operation: any; +} +export interface ConcreteBatchRequest { + kind: string; + operationKind: string; + name: string; + metadata: {[key: string]: any}; + fragment: ConcreteFragment; + requests: Array<{ + name: string; + id: string | null; + text: string | null; + argumentDependencies: any[] | null; + operation: any; + }>; +} + +export function getRequest(taggedNode: GraphQLTaggedNode): ConcreteRequest; export type RequestNode = ConcreteRequest | ConcreteBatchRequest; From 3b59425df7db3cad1cc4c224fa8aecd193de3f09 Mon Sep 17 00:00:00 2001 From: Dalius Dobravolskas Date: Mon, 28 Jan 2019 12:00:40 +0200 Subject: [PATCH 246/312] Initial State support for reduceReducers. --- types/reduce-reducers/index.d.ts | 76 +++++++- .../reduce-reducers/reduce-reducers-tests.ts | 183 +++++++++++++++++- 2 files changed, 254 insertions(+), 5 deletions(-) diff --git a/types/reduce-reducers/index.d.ts b/types/reduce-reducers/index.d.ts index d4bde0bc8a..19499c452c 100644 --- a/types/reduce-reducers/index.d.ts +++ b/types/reduce-reducers/index.d.ts @@ -1,7 +1,81 @@ -// Type definitions for reduce-reducers 0.1 +// Type definitions for reduce-reducers 0.2 // Project: https://github.com/acdlite/reduce-reducers // Definitions by: Huy Nguyen +// Dalius Dobravolskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Reducer } from 'redux'; +export default function reduceReducer(r0: Reducer, s: S | null): Reducer; +export default function reduceReducer(r0: Reducer, r1: Reducer, s: S | null): Reducer; +export default function reduceReducer(r0: Reducer, r1: Reducer, r2: Reducer, s: S | null): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + r8: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + r8: Reducer, + r9: Reducer, + s: S | null, +): Reducer; export default function reduceReducer(...reducers: Array>): Reducer; diff --git a/types/reduce-reducers/reduce-reducers-tests.ts b/types/reduce-reducers/reduce-reducers-tests.ts index f542fe834a..f4fdd8fff3 100644 --- a/types/reduce-reducers/reduce-reducers-tests.ts +++ b/types/reduce-reducers/reduce-reducers-tests.ts @@ -1,13 +1,188 @@ import { - Reducer, - Action, + Reducer, + Action, } from 'redux'; import reduceReducers from 'reduce-reducers'; interface TestStore { - a: number; - b: string; + a: number; + b: string; } const firstReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; const secondReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; const finalReducer: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer); +const finalReducerWithState: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer, null); + +const initialState: TestStore = { + a: 1, + b: '2', +}; + +const finalReducerWithInitialState: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + initialState); + +const reducer02: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer03: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer04: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer05: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer06: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer07: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer08: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer09: (state: TestStore, action: Action) => TestStore = (a, b) => a; + +const finalReducerWithInitialState02: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + initialState); +const finalReducerWithInitialState02null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + null); + +const finalReducerWithInitialState03: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + initialState); +const finalReducerWithInitialState03null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + null); + +const finalReducerWithInitialState04: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + initialState); +const finalReducerWithInitialState04null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + null); + +const finalReducerWithInitialState05: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + initialState); +const finalReducerWithInitialState05null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + null); + +const finalReducerWithInitialState06: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + initialState); +const finalReducerWithInitialState06null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + null); + +const finalReducerWithInitialState07: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + initialState); +const finalReducerWithInitialState07null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + null); + +const finalReducerWithInitialState08: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + initialState); +const finalReducerWithInitialState08null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + null); + +const finalReducerWithoutInitialState09: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09); +const finalReducerWithInitialState09: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09, + initialState); +const finalReducerWithInitialState09null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09, + null); From 67a1afed1e485dd1e8040318fba2927ba86a7997 Mon Sep 17 00:00:00 2001 From: fraukesch Date: Thu, 31 Jan 2019 10:20:23 +0100 Subject: [PATCH 247/312] Added missing property to DroppableStateSnapshot See: https://github.com/atlassian/react-beautiful-dnd#2-snapshot-droppablestatesnapshot --- types/react-beautiful-dnd/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index 085ad4e8b7..cb59017e52 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -53,6 +53,7 @@ export interface DroppableProvided { export interface DroppableStateSnapshot { isDraggingOver: boolean; + draggingOverWith?: DraggableId; } export interface DroppableProps { From d40ad92baf8a39a07c01ea1cb92473b51d7e6943 Mon Sep 17 00:00:00 2001 From: amirfuhaira Date: Thu, 31 Jan 2019 17:34:23 +0800 Subject: [PATCH 248/312] [cron] update types to 1.6 --- types/cron/index.d.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index b27bfdf90c..596a9536ca 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.3 +// Type definitions for cron 1.6 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Lundarl Gholoi @@ -9,8 +9,9 @@ export declare class CronTime { * Create a new ```CronTime```. * @param source The time to fire off your job. This can be in the form of cron syntax or a JS ```Date``` object. * @param zone Timezone name. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * @param utcOffset UTC offset. Don't use both ```zone``` and ```utcOffset``` together or weird things may happen. */ - constructor(source: string | Date, zone?: string); + constructor(source: string | Date, zone?: string, utcOffset?: string | number); /** * Tells you when ```CronTime``` will be run. @@ -29,19 +30,19 @@ export declare interface CronJobParameters { */ cronTime: string | Date; /** - * The function to fire at the specified time. + * The function to fire at the specified time. If an ```onComplete``` callback was provided, ```onTick``` will receive it as an argument. ```onTick``` may call ```onComplete``` when it has finished its work. */ onTick: () => void; /** - * A function that will fire when the job is complete, when it is stopped. + * A function that will fire when the job is stopped with ```job.stop()```, and may also be called by ```onTick``` at the end of each run. */ onComplete?: () => void; /** - * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your onTick function, it just gives you more control over the behavior of your jobs. + * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your ```onTick``` function, it just gives you more control over the behavior of your jobs. */ start?: boolean; /** - * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. */ timeZone?: string; /** @@ -52,6 +53,14 @@ export declare interface CronJobParameters { * This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. */ runOnInit?: boolean; + /** + * This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + */ + utcOffset?: string | number; + /** + * If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. + */ + unrefTimeout?: boolean; } export declare class CronJob { @@ -73,8 +82,10 @@ export declare class CronJob { * @param timeZone Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). * @param context The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call ```this.stop()```. However, if you change this you'll have access to the functions and values within your context object. * @param runOnInit This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. + * @param utcOffset This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + * @param unrefTimeout If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. */ - constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean); + constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); /** * Create a new ```CronJob```. * @param options Job parameters. @@ -111,7 +122,7 @@ export declare class CronJob { } export declare var job: - ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean) => CronJob) + ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) | ((options: CronJobParameters) => CronJob); export declare var time: (source: string | Date, zone?: string) => CronTime; export declare var sendAt: (cronTime: CronTime) => Date; From af0e0c5c319e6c63bbe8d39d770e2eb45672f05f Mon Sep 17 00:00:00 2001 From: Lee Henson Date: Thu, 31 Jan 2019 10:12:00 +0000 Subject: [PATCH 249/312] [http-aws-es] type awsConfig as AWS.Config instead of handcrafted subset --- types/http-aws-es/http-aws-es-tests.ts | 29 +++++++++++++------------- types/http-aws-es/index.d.ts | 11 ++-------- 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/types/http-aws-es/http-aws-es-tests.ts b/types/http-aws-es/http-aws-es-tests.ts index acd5248817..18ae2b666c 100644 --- a/types/http-aws-es/http-aws-es-tests.ts +++ b/types/http-aws-es/http-aws-es-tests.ts @@ -1,42 +1,43 @@ -import { EnvironmentCredentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; import { Client } from "elasticsearch"; import HttpAmazonESConnector = require("http-aws-es"); new Client({ - awsConfig: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - awsConfig: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); -const myCredentials = new EnvironmentCredentials("AWS"); +const myCredentials = new AWS.EnvironmentCredentials("AWS"); + new Client({ - awsConfig: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - awsConfig: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index 15a803076f..2a6ca11629 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -7,18 +7,11 @@ /// import * as e from "elasticsearch"; -import { Credentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; declare module "elasticsearch" { - interface AmazonESOptions { - accessKey?: string; - credentials?: Credentials; - region: string; - secretKey?: string; - } - interface ConfigOptions { - awsConfig?: AmazonESOptions; + awsConfig?: AWS.Config; } } From 4ecff0071745b47ad1e1d23e22dd3fe27bc22bcc Mon Sep 17 00:00:00 2001 From: Ahmed Abdelmotey Date: Thu, 31 Jan 2019 12:25:31 +0200 Subject: [PATCH 250/312] Update chartist-tests.ts Added simple tests to verify types changes --- types/chartist/chartist-tests.ts | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index cb7f884264..863fdb33be 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -485,3 +485,53 @@ new Chartist.Candle('.ct-chart', { } } }); + + +// Create a simple bar chart and line chart with two dimensional arrays +new Chartist.Bar('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) + +new Chartist.Line('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) From c4c2c7095ee6b6231061518c15e66a6e855b28df Mon Sep 17 00:00:00 2001 From: Ahmed Abdelmotey Date: Thu, 31 Jan 2019 12:40:11 +0200 Subject: [PATCH 251/312] Updated IChartistData type Bar charts and line charts needs to be two dimensional arrays, this was not available in the allowed types --- types/chartist/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chartist/index.d.ts b/types/chartist/index.d.ts index 9b096839cc..8d700703c9 100644 --- a/types/chartist/index.d.ts +++ b/types/chartist/index.d.ts @@ -93,7 +93,7 @@ declare namespace Chartist { // TODO: come in and tidy this up and make it fit better interface IChartistData { labels?: Array | Array | Array; - series: Array | Array> | Array | Array>; + series: Array | Array> | Array> | Array | Array>; } interface IChartistSeriesData { From 04f251145f4902603a748e4db5bfc89f100e2d0f Mon Sep 17 00:00:00 2001 From: Robert Ying Date: Thu, 31 Jan 2019 18:56:27 +0800 Subject: [PATCH 252/312] [expo/vector-icons] add AntDesign type --- types/expo__vector-icons/expo__vector-icons-tests.tsx | 10 +++++----- types/expo__vector-icons/index.d.ts | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/types/expo__vector-icons/expo__vector-icons-tests.tsx b/types/expo__vector-icons/expo__vector-icons-tests.tsx index 7d918c917f..33e1056957 100644 --- a/types/expo__vector-icons/expo__vector-icons-tests.tsx +++ b/types/expo__vector-icons/expo__vector-icons-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { View, Text, TabBarIOS } from 'react-native'; -import { createIconSet, MaterialIcons, FontAwesome, Ionicons } from 'expo__vector-icons'; +import { createIconSet, MaterialIcons, FontAwesome, AntDesign } from 'expo__vector-icons'; const glyphMap = { custom: 58918 @@ -48,7 +48,7 @@ class TabTest extends React.Component<{}, { selectedTab: string }> { render() { return ( - { onPress={() => this.setState({ selectedTab: 'tab1' })} > - + - { onPress={() => this.setState({ selectedTab: 'tab2' })} > - + ); } diff --git a/types/expo__vector-icons/index.d.ts b/types/expo__vector-icons/index.d.ts index 529142c0e9..ab7db3547b 100644 --- a/types/expo__vector-icons/index.d.ts +++ b/types/expo__vector-icons/index.d.ts @@ -1,13 +1,16 @@ -// Type definitions for @expo/vector-icons 6.2 +// Type definitions for @expo/vector-icons 9.0.0 // Project: https://github.com/expo/vector-icons // Definitions by: Hyeonsu Lee +// Robert Ying // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; import { TextProps } from 'react-native'; +import { Icon } from 'react-native-vector-icons/Icon'; export { createIconSet, createIconSetFromFontello, createIconSetFromIcoMoon } from 'react-native-vector-icons'; +export { Icon as AntDesign }; export { default as Entypo } from 'react-native-vector-icons/Entypo'; export { default as EvilIcons } from 'react-native-vector-icons/EvilIcons'; export { default as Feather } from 'react-native-vector-icons/Feather'; From 60fd6dcb117d3402e4a3fb047d8260380d0f1bbb Mon Sep 17 00:00:00 2001 From: Robert Ying Date: Thu, 31 Jan 2019 19:45:05 +0800 Subject: [PATCH 253/312] [expo/vector-icons] omit patch version --- types/expo__vector-icons/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/expo__vector-icons/index.d.ts b/types/expo__vector-icons/index.d.ts index ab7db3547b..7a7ac587ec 100644 --- a/types/expo__vector-icons/index.d.ts +++ b/types/expo__vector-icons/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @expo/vector-icons 9.0.0 +// Type definitions for @expo/vector-icons 9.0 // Project: https://github.com/expo/vector-icons // Definitions by: Hyeonsu Lee // Robert Ying From 2bcbb3d221111160ef035bff8b9cec9559d3a269 Mon Sep 17 00:00:00 2001 From: Alex Brick Date: Thu, 31 Jan 2019 12:47:22 +0100 Subject: [PATCH 254/312] [content-range] Adding types for content-range module --- types/content-range/content-range-tests.ts | 23 ++++++++++++++++++++++ types/content-range/index.d.ts | 22 +++++++++++++++++++++ types/content-range/tsconfig.json | 23 ++++++++++++++++++++++ types/content-range/tslint.json | 1 + 4 files changed, 69 insertions(+) create mode 100644 types/content-range/content-range-tests.ts create mode 100644 types/content-range/index.d.ts create mode 100644 types/content-range/tsconfig.json create mode 100644 types/content-range/tslint.json diff --git a/types/content-range/content-range-tests.ts b/types/content-range/content-range-tests.ts new file mode 100644 index 0000000000..c482d6f072 --- /dev/null +++ b/types/content-range/content-range-tests.ts @@ -0,0 +1,23 @@ +import { format, parse } from 'content-range'; + +format({ + first: 10, + last: 100, + length: 100, + limit: 20, + unit: 'items', +}); + +format({ + length: null, + unit: 'bytes', +}); + +const parts = parse('items 10-29/100'); + +if (parts) { + parts.first; + parts.last; + parts.length; + parts.unit; +} diff --git a/types/content-range/index.d.ts b/types/content-range/index.d.ts new file mode 100644 index 0000000000..b8ee780541 --- /dev/null +++ b/types/content-range/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for content-range 1.1 +// Project: https://github.com/neoziro/content-range +// Definitions by: Alex Brick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ContentRangeFormatOptions { + first?: number; + last?: number; + length: number | null; + limit?: number; + unit: string; +} + +export interface ContentRangeParts { + first: number | null; + last: number | null; + length: number | null; + unit: string; +} + +export function format(options: ContentRangeFormatOptions): string; +export function parse(str: string): ContentRangeParts | null; diff --git a/types/content-range/tsconfig.json b/types/content-range/tsconfig.json new file mode 100644 index 0000000000..a2649416e0 --- /dev/null +++ b/types/content-range/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "content-range-tests.ts" + ] +} diff --git a/types/content-range/tslint.json b/types/content-range/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/content-range/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 03aabe8cc0414432547386bbe9eb2c5315f88e77 Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Thu, 31 Jan 2019 10:35:06 -0200 Subject: [PATCH 255/312] fix required export modification --- types/mem-cache/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts index f5e135a363..df2a0db47d 100644 --- a/types/mem-cache/index.d.ts +++ b/types/mem-cache/index.d.ts @@ -5,13 +5,13 @@ import { EventEmitter } from 'events'; -export interface CacheOptions { +interface CacheOptions { timeout?: number; doesNotRenewTimeout?: boolean; timeoutDisabled?: boolean; } -export default class Cache extends EventEmitter { +declare class Cache extends EventEmitter { keys: string[]; length: number; @@ -22,3 +22,5 @@ export default class Cache extends EventEmitter { remove(key: string): void; clean(): void; } + +export = Cache; From 05bddbd67ca8bfd58b51ceba24c68a790aec04c9 Mon Sep 17 00:00:00 2001 From: MutterPedro Date: Thu, 31 Jan 2019 10:43:46 -0200 Subject: [PATCH 256/312] fix required export/import modification --- types/mem-cache/mem-cache-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mem-cache/mem-cache-tests.ts b/types/mem-cache/mem-cache-tests.ts index 2b667258d3..747ffd75c2 100644 --- a/types/mem-cache/mem-cache-tests.ts +++ b/types/mem-cache/mem-cache-tests.ts @@ -1,4 +1,4 @@ -import Cache from 'mem-cache'; +import Cache = require('mem-cache'); const cache = new Cache(); // $ExpectType Cache From ec2f9a6164c011fcf6fce0de6c7ee005b99d3b80 Mon Sep 17 00:00:00 2001 From: andrewroyburk Date: Wed, 30 Jan 2019 17:46:17 +0100 Subject: [PATCH 257/312] pickaday: correct naming of boolean method parameter on `setDate` --- types/pikaday/index.d.ts | 2 +- types/pikaday/pikaday-tests.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/pikaday/index.d.ts b/types/pikaday/index.d.ts index 63967d3169..fae7acf93a 100644 --- a/types/pikaday/index.d.ts +++ b/types/pikaday/index.d.ts @@ -44,7 +44,7 @@ declare class Pikaday { * can optionally be passed as the second parameter to prevent triggering * of the onSelect callback, allowing the date to be set silently. */ - setDate(date: string | Date, triggerOnSelect?: boolean): void; + setDate(date: string | Date, preventOnSelect?: boolean): void; /** * Returns a Moment.js object for the selected date (Moment must be diff --git a/types/pikaday/pikaday-tests.ts b/types/pikaday/pikaday-tests.ts index 14250d0df3..984961b99d 100644 --- a/types/pikaday/pikaday-tests.ts +++ b/types/pikaday/pikaday-tests.ts @@ -30,6 +30,7 @@ new Pikaday({field: $('#datepicker')[0]}); picker.toString('YYYY-MM-DD'); picker.getDate(); picker.setDate('2015-01-01'); + picker.setDate('2015-01-01', true); picker.getMoment(); picker.setMoment(moment('14th February 2014', 'DDo MMMM YYYY')); picker.setMoment(moment('14th February 2014', 'DDo MMMM YYYY'), true); From 450ce9d6824537502c8e268705532f107172f29e Mon Sep 17 00:00:00 2001 From: andrewroyburk Date: Wed, 30 Jan 2019 17:48:20 +0100 Subject: [PATCH 258/312] pickaday: add explicit null types to match usage for clearing min/max dates --- types/pikaday/index.d.ts | 4 ++-- types/pikaday/pikaday-tests.ts | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/pikaday/index.d.ts b/types/pikaday/index.d.ts index fae7acf93a..3adb7fc340 100644 --- a/types/pikaday/index.d.ts +++ b/types/pikaday/index.d.ts @@ -90,12 +90,12 @@ declare class Pikaday { /** * Update the minimum/earliest date that can be selected. */ - setMinDate(date: Date): void; + setMinDate(date: Date | null): void; /** * Update the maximum/latest date that can be selected. */ - setMaxDate(date: Date): void; + setMaxDate(date: Date | null): void; /** * Update the range start date. For using two Pikaday instances to diff --git a/types/pikaday/pikaday-tests.ts b/types/pikaday/pikaday-tests.ts index 984961b99d..7a532efb6f 100644 --- a/types/pikaday/pikaday-tests.ts +++ b/types/pikaday/pikaday-tests.ts @@ -42,6 +42,8 @@ new Pikaday({field: $('#datepicker')[0]}); picker.gotoYear(2015); picker.setMinDate(new Date()); picker.setMaxDate(new Date()); + picker.setMinDate(null); + picker.setMaxDate(null); picker.setStartRange(new Date()); picker.setEndRange(new Date()); picker.isVisible(); From 4bdc8452acf58d12c897fa5b77434b3afe9b28da Mon Sep 17 00:00:00 2001 From: Jessica Date: Thu, 31 Jan 2019 22:01:05 +0900 Subject: [PATCH 259/312] Update contributor credits --- types/emoji-mart/index.d.ts | 2 +- types/qhistory/index.d.ts | 2 +- types/react-loadable/index.d.ts | 2 +- types/react/index.d.ts | 2 +- types/styled-components/index.d.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts index a92bcb77ff..8ea741ca9f 100644 --- a/types/emoji-mart/index.d.ts +++ b/types/emoji-mart/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Nick Winans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 6269c25e82..bf278de47d 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for qhistory 1.0 // Project: https://github.com/pshrmn/qhistory#readme -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index 8661716e75..2e38f58c39 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-loadable 5.5 // Project: https://github.com/thejameskyle/react-loadable#readme -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Oden S. // Ian Ker-Seymer // Tomek Łaziuk diff --git a/types/react/index.d.ts b/types/react/index.d.ts index d98c0e03a2..a87874b9fd 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -18,7 +18,7 @@ // Olivier Pascal // Martin Hochel // Frank Li -// Jessica Franco +// Jessica Franco // Paul Sherman // Sunil Pai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 1ab41d31e1..924699dd3a 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Ihor Chulinda // Adam Lavin -// Jessica Franco +// Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 From feed7babde6198acf1f550634c7e3f575e94ef56 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Thu, 31 Jan 2019 22:12:42 +0800 Subject: [PATCH 260/312] remove unused types as addressed by Jessidhia --- types/redux-state-sync/index.d.ts | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts index 755d354707..cfb7dda234 100644 --- a/types/redux-state-sync/index.d.ts +++ b/types/redux-state-sync/index.d.ts @@ -8,11 +8,6 @@ import { Store, Reducer, Middleware, AnyAction } from "redux"; import BroadcastChannel from "broadcast-channel"; -export let lastUuid: number; -export const GET_INIT_STATE: string; -export const SEND_INIT_STATE: string; -export const RECEIVE_INIT_STATE: string; - export interface Stamp { $uuid: string; $wuid: string; @@ -33,19 +28,6 @@ export interface MessageListenerConfig { allowed: (type?: string) => boolean; } -export const defaultConfig: Config; -export const WINDOW_STATE_SYNC_ID: string; -export let isMessageListenerCreated: boolean; - -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; - -export function getIniteState(): AnyAction; -export function sendIniteState(): AnyAction; -export function receiveIniteState(store: Store): AnyAction; -export function s4(): string; -export function guid(): string; - export function generateUuidForAction(action: AnyAction): StampedAction; export function isActionAllowed(config: Config): (type?: any) => boolean; export function createMessageListener(config: MessageListenerConfig): void; From f423c53701bbc45f0e39a555a7c0e65a4ee574b6 Mon Sep 17 00:00:00 2001 From: AOHUA MU Date: Thu, 31 Jan 2019 22:14:37 +0800 Subject: [PATCH 261/312] fix type issue --- types/redux-state-sync/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts index cfb7dda234..fb7e0f84b5 100644 --- a/types/redux-state-sync/index.d.ts +++ b/types/redux-state-sync/index.d.ts @@ -29,7 +29,7 @@ export interface MessageListenerConfig { } export function generateUuidForAction(action: AnyAction): StampedAction; -export function isActionAllowed(config: Config): (type?: any) => boolean; +export function isActionAllowed(config: Config): (type: string) => boolean; export function createMessageListener(config: MessageListenerConfig): void; export function createStateSyncMiddleware(config?: Config): Middleware; export function withReduxStateSync( From 80ac20f080f30995e4a121b76599c91b28beafd2 Mon Sep 17 00:00:00 2001 From: denis Date: Thu, 31 Jan 2019 15:27:32 +0100 Subject: [PATCH 262/312] Update to 1.3.3 Add d3.stackOrderAppearance. --- types/d3-shape/d3-shape-tests.ts | 1 + types/d3-shape/index.d.ts | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index fb79b15e4a..1ce464093f 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -1464,6 +1464,7 @@ seriesDatum = seriesPoint.data; let order: number[]; const seriesAnyAny: d3Shape.Series = seriesArray[0]; +order = d3Shape.stackOrderAppearance(seriesAnyAny); order = d3Shape.stackOrderAscending(seriesAnyAny); order = d3Shape.stackOrderDescending(seriesAnyAny); order = d3Shape.stackOrderInsideOut(seriesAnyAny); diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index ed64d6f827..e4f1fba6b3 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 1.2.0 +// Last module patch version validated against: 1.3.3 import { Path } from 'd3-path'; @@ -2670,6 +2670,13 @@ export function stack(): Stack; */ export function stack(): Stack; +/** + * Returns a series order such that the earliest series (according to the maximum value) is at the bottom. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderAppearance(series: Series): number[]; + /** * Returns a series order such that the smallest series (according to the sum of values) is at the bottom. * From 150df3dc1e62cf308abfea903cfdb4ee9cf99c3e Mon Sep 17 00:00:00 2001 From: licui Date: Thu, 31 Jan 2019 09:50:49 -0500 Subject: [PATCH 263/312] Remove unused file --- .../interappbus/channel/channels-docs.d.ts | 266 ------------------ 1 file changed, 266 deletions(-) delete mode 100644 types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts diff --git a/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts b/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts deleted file mode 100644 index fed5208e2e..0000000000 --- a/types/openfin/_v2/api/interappbus/channel/channels-docs.d.ts +++ /dev/null @@ -1,266 +0,0 @@ -declare const InterApplicationBus: any; -/** - * Instance created to enable use of a channel as a provider. Allows for communication with the {@link Channel#ChannelClient ChannelClients} by invoking an action on - * a single client via {@link Channel#ChannelProvider#dispatch dispatch} or all clients via {@link Channel#ChannelProvider#publish publish} - * and to listen for communication from clients by registering an action via {@link Channel#ChannelProvider#register register}. - * - * ##### Constructor - * - * Returned by {@link Channel.create Channel.create}. - * - * ##### Synchronous Methods - * * {@link Channel#ChannelProvider#destroy destroy()} - * * {@link Channel#ChannelProvider#publish publish(action, payload)} - * * {@link Channel#ChannelProvider#register register(action, listener)} - * * {@link Channel#ChannelProvider#remove remove(action)} - * - * ##### Asynchronous Methods - * * {@link Channel#ChannelProvider#dispatch dispatch(to, action, payload)} - * - * ##### Middleware - * Middleware functions receive the following arguments: (action, payload, senderId). - * The return value of the middleware function will be passed on as the payload from beforeAction, to the action listener, to afterAction - * unless it is undefined, in which case the most recently defined payload is used. Middleware can be used for side effects. - * * {@link Channel#ChannelProvider#setDefaultAction setDefaultAction(middleware)} - * * {@link Channel#ChannelProvider#onError onError(middleware)} - * * {@link Channel#ChannelProvider#beforeAction beforeAction(middleware)} - * * {@link Channel#ChannelProvider#afterAction afterAction(middleware)} - * - * @memberof! Channel# - * @hideconstructor - */ -declare class ChannelProvider { - constructor(); - /** - * - * Destroy the channel. - * @returns {Promise} - */ - destroy(): void; - /** - * - * Dispatch an action to a specified client. Returns a promise for the result of executing that action on the client side. - * @param {Identity} to - Identity of the target client. - * @param {string} action - Name of the action to be invoked by the client. - * @param {*} payload - Payload to be sent along with the action. - * @returns {Promise} - * @tutorial Channel.tutorial - */ - dispatch(): void; - /** - * - * Register an action to be called - * @param {string} action - Name of the action to be registered for channel clients to later invoke. - * @param {Action} listener - Function representing the action to be taken on a client dispatch. - * @returns {boolean} - Boolean representing the successful registration of the action. - * @tutorial Channel.tutorial - */ - register(): void; - /** - * - * Publish an action and payload to every connected client. - * Synchronously returns an array of promises for each action (see dispatch). - * @param {string} action - * @param {*} payload - * @tutorial Channel.tutorial - */ - publish(): void; - /** - * - * Register a listener that is called on every new client connection. - * It is passed the identity of the connecting client and a payload if it was provided to {@link Channel.connect}. - * If you wish to reject the connection, throw an error. Be sure to synchronously provide an onConnection upon receipt of the channelProvider - * to ensure all potential client connections are caught by the listener. - * @param {Channel#ChannelProvider~ConnectionListener} listener - * @tutorial Channel.tutorial - */ - onConnection(): void; - /** - * - * Register a listener that is called on every new client disconnection. - * It is passed the disconnection event of the disconnecting client. - * @param {Channel~ConnectionEvent} listener - * @tutorial Channel.tutorial - */ - onDisconnection(): void; - /** - * - * Register middleware that fires before the action. - * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed before invoking the action. - * @tutorial Channel.middleware - */ - beforeAction(): void; - /** - * - * Register an error handler. This is called before responding on any error. - * @param {function} middleware - Function to be executed in case of an error. - * @tutorial Channel.middleware - */ - onError(): void; - /** - * - * Register middleware that fires after the action. This is passed the return value of the action. - * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed after invoking the action. - * @tutorial Channel.middleware - */ - afterAction(): void; - /** - * - * Remove an action by action name. - * @param {string} action - Name of the action to be removed. - * @tutorial Channel.tutorial - */ - remove(): void; - /** - * - * Sets a default action. This is used any time an action that has not been registered is invoked. - * Default behavior if not set is to throw an error. - * @param {Channel#ChannelProvider~Middleware} middleware - Function to be executed when a client invokes an action name that has not been registered. - * @tutorial Channel.middleware - */ - setDefaultAction(): void; -} -/** - * Instance created to enable use of a channel as a client. Allows for communication with the - * {@link Channel#ChannelProvider ChannelProvider} by invoking an action on the - * provider via {@link Channel#ChannelClient#dispatch dispatch} and to listen for communication - * from the provider by registering an action via {@link Channel#ChannelClient#register register}. - * - * ##### Constructor - * Returned by {@link Channel.connect Channel.connect}. - * - * ##### Synchronous Methods - * * {@link Channel#ChannelClient#disconnect disconnect()} - * * {@link Channel#ChannelClient#register register(action, listener)} - * * {@link Channel#ChannelClient#remove remove(action)} - * - * ##### Asynchronous Methods - * * {@link Channel#ChannelClient#dispatch dispatch(to, action, payload)} - * - * ##### Middleware - * Middleware functions receive the following arguments: (action, payload, senderId). - * The return value of the middleware function will be passed on as the payload from beforeAction, to the action listener, to afterAction - * unless it is undefined, in which case the original payload is used. Middleware can be used for side effects. - * * {@link Channel#ChannelClient#setDefaultAction setDefaultAction(middleware)} - * * {@link Channel#ChannelClient#onError onError(middleware)} - * * {@link Channel#ChannelClient#beforeAction beforeAction(middleware)} - * * {@link Channel#ChannelClient#afterAction afterAction(middleware)} - * - * @hideconstructor - * @memberof! Channel# - */ -declare class ChannelClient { - constructor(); - /** - * - * Disconnect from the channel. - * @returns {Promise} - */ - disconnect(): void; - /** - * - * Dispatch the given to the channel provider. Returns a promise that resolves with the response from the provider for that action. - * @param {string} action - Name of the action to be invoked by the channel provider. - * @param {*} payload - Payload to be sent along with the action. - * @tutorial Channel.tutorial - * @returns {Promise} - */ - dispatch(): void; - /** - * - * Register an action to be called by the provider of the channel. - * @param {string} action - Name of the action to be registered for the channel provider to later invoke. - * @param {Action} listener - Function representing the action to be taken on a provider dispatch. - * @tutorial Channel.tutorial - */ - register(): void; - /** - * - * Register middleware that fires before the action. - * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed before invoking the action. - * @tutorial Channel.middleware - */ - beforeAction(): void; - /** - * - * Register a listener that is called on channel disconnection. - * It is passed the disconnection event of the disconnecting channel. - * @param {Channel~ConnectionEvent} listener - * @tutorial Channel.tutorial - */ - onDisconnection(): void; - /** - * Register an error handler. This is called before responding on any error. - * @param {function} middleware - Function to be executed in case of an error. - * @tutorial Channel.middleware - */ - onError(): void; - /** - * - * Register middleware that fires after the action. This is passed the return value of the action. - * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed after invoking the action. - * @tutorial Channel.middleware - */ - afterAction(): void; - /** - * - * Remove an action by action name. - * @param {string} action - Name of the action to be removed. - * @tutorial Channel.tutorial - */ - remove(): void; - /** - * - * Sets a default action. This is used any time an action that has not been registered is invoked. - * Default behavior if not set is to throw an error. - * @param {Channel#ChannelClient~Middleware} middleware - Function to be executed when a client invokes an action name that has not been registered. - * @tutorial Channel.middleware - */ - setDefaultAction(): void; -} -/** - * Channel action callback signature - * @callback Channel#ChannelProvider~Action - * @param {*} payload - Payload sent along with the message. - * @param {Identity} identity - Identity of the sender. -*/ -/** - * Channel action callback signature - * @callback Channel#ChannelClient~Action - * @param {*} payload - Payload sent along with the message. - * @param {Identity} identity - Identity of the sender. -*/ -/** - * Middleware function signature - * @callback Channel#ChannelProvider~Middleware - * @param {string} action - Action to be invoked. - * @param {*} payload - Payload sent along with the message (or error for error middleware). - * @param {Identity} identity - Identity of the sender. -*/ -/** - * Middleware function signature - * @callback Channel#ChannelClient~Middleware - * @param {string} action - Action to be invoked. - * @param {*} payload - Payload sent along with the message. - * @param {Identity} identity - Identity of the sender. -*/ -/** - * Callback for the channel onConnection or onDisconnection. If it errors connection will be rejected. - * @callback Channel#ChannelProvider~ConnectionListener - * @param {Identity} identity - Identity of the client attempting to connect to the channel. - * @param {*} payload - Payload sent with connection request. -*/ -/** - * Callback for onChannelConnect or onChannelDisconnect. - * @typedef {object} Channel~ConnectionEvent - * @property {string} channelId - Identifier of the channel. - * @property {string} uuid - Channel provider uuid. - * @property {string} [name] - Channel provider name. - * @property {string} channelName - Name of the channel. - */ -/** - * @typedef {object} Channel~ConnectOptions - * @property {*} [payload] - Payload to pass to ChannelProvider onConnection action. - * @property {boolean} [wait=true] - If true will wait for ChannelProvider to connect. If false will fail if ChannelProvider is not found. - * - */ From 5dfa87b3f1f3c2f0b0e837ba3064975ebbadb63c Mon Sep 17 00:00:00 2001 From: licui Date: Thu, 31 Jan 2019 09:59:27 -0500 Subject: [PATCH 264/312] Fix path issue --- types/openfin/v37/tsconfig.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/openfin/v37/tsconfig.json b/types/openfin/v37/tsconfig.json index 1847c9c9d2..b054254a07 100644 --- a/types/openfin/v37/tsconfig.json +++ b/types/openfin/v37/tsconfig.json @@ -14,6 +14,11 @@ "../../" ], "types": [], + "paths": { + "openfin": [ + "openfin/v37" + ] + }, "noEmit": true, "forceConsistentCasingInFileNames": true }, From b0e7a55053036d1a2e89c1d5f9e8ac1fe9131645 Mon Sep 17 00:00:00 2001 From: gretzky Date: Thu, 31 Jan 2019 10:13:59 -0500 Subject: [PATCH 265/312] [styled-system] fix breakpoints type --- types/styled-system/index.d.ts | 399 +++++++++++++++++---------------- 1 file changed, 201 insertions(+), 198 deletions(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index aa94ab2aed..1207718523 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -9,42 +9,45 @@ // Adam Lavin // Joachim Schuler // Adam Misiorny +// Sara F-P // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as CSS from "csstype"; +import * as CSS from 'csstype' -export const defaultBreakpoints: string[]; -export function is(n: any): boolean; -export function num(n: any): boolean; -export function px(n: any): string; +export const defaultBreakpoints: string[] +export function is(n: any): boolean +export function num(n: any): boolean +export function px(n: any): string -export function get(obj: any, ...paths: Array): any; +export function get(obj: any, ...paths: Array): any -export function themeGet(keys: string, fallback?: string): any; -export function cloneFunc(fn: (...args: any[]) => any): (...args: any[]) => any; +export function themeGet(keys: string, fallback?: string): any +export function cloneFunc(fn: (...args: any[]) => any): (...args: any[]) => any -export function merge(a: any, b: any): any; +export function merge(a: any, b: any): any export function compose( ...funcs: Array<(...args: any[]) => any> -): (...args: any[]) => any; +): (...args: any[]) => any -export function createMediaQuery(n: number | string): string; +export function createMediaQuery(n: number | string): string export interface LowLevelStylefunctionArguments { - prop: string; - cssProperty?: string; - key?: string; - getter?: () => any; - transformValue?: (n: string | number) => any; - scale?: Array; + prop: string + cssProperty?: string + key?: string + getter?: () => any + transformValue?: (n: string | number) => any + scale?: Array } -export function style(args: LowLevelStylefunctionArguments): {[cssProp: string]: string}; +export function style( + args: LowLevelStylefunctionArguments +): { [cssProp: string]: string } -export type TLengthStyledSystem = string | 0 | number; -export type ResponsiveValue = T | Array | { [key: string]: T }; +export type TLengthStyledSystem = string | 0 | number +export type ResponsiveValue = T | Array | { [key: string]: T } /** * Converts shorthand margin and padding props to margin and padding CSS declarations @@ -58,71 +61,71 @@ export type ResponsiveValue = T | Array | { [key: string]: T }; export interface SpaceProps { /** Margin on top, left, bottom and right */ - m?: ResponsiveValue>; + m?: ResponsiveValue> /** Margin for the top */ - mt?: ResponsiveValue>; + mt?: ResponsiveValue> /** Margin for the right */ - mr?: ResponsiveValue>; + mr?: ResponsiveValue> /** Margin for the bottom */ - mb?: ResponsiveValue>; + mb?: ResponsiveValue> /** Margin for the left */ - ml?: ResponsiveValue>; + ml?: ResponsiveValue> /** Margin for the left and right */ - mx?: ResponsiveValue>; + mx?: ResponsiveValue> /** Margin for the top and bottom */ - my?: ResponsiveValue>; + my?: ResponsiveValue> /** Padding on top, left, bottom and right */ - p?: ResponsiveValue>; + p?: ResponsiveValue> /** Padding for the top */ - pt?: ResponsiveValue>; + pt?: ResponsiveValue> /** Padding for the right */ - pr?: ResponsiveValue>; + pr?: ResponsiveValue> /** Padding for the bottom */ - pb?: ResponsiveValue>; + pb?: ResponsiveValue> /** Padding for the left */ - pl?: ResponsiveValue>; + pl?: ResponsiveValue> /** Padding for the left and right */ - px?: ResponsiveValue>; + px?: ResponsiveValue> /** Padding for the top and bottom */ - py?: ResponsiveValue>; + py?: ResponsiveValue> } -export function space(...args: any[]): any; +export function space(...args: any[]): any export interface VariantArgs { - key?: string; + key?: string // Defaults to "variant" - prop?: string; + prop?: string } -export function variant(props: VariantArgs): (...args: any[]) => any; +export function variant(props: VariantArgs): (...args: any[]) => any -export type ObjectOrArray = T[] | { [K: string]: T }; +export type ObjectOrArray = T[] | { [K: string]: T } export interface BaseTheme { - breakpoints?: number[]; - colors?: ObjectOrArray; - fontSizes?: number[]; - space?: number[]; + breakpoints?: string[] + colors?: ObjectOrArray + fontSizes?: number[] + space?: number[] } export interface Theme extends BaseTheme { - borders?: ObjectOrArray>; - buttons?: ObjectOrArray; - colorStyles?: ObjectOrArray; - fontWeights?: ObjectOrArray; - fonts?: ObjectOrArray; - heights?: ObjectOrArray>; - letterSpacings?: ObjectOrArray>; - lineHeights?: ObjectOrArray>; - maxHeights?: ObjectOrArray>; - maxWidths?: ObjectOrArray>; - minHeights?: ObjectOrArray>; - minWidths?: ObjectOrArray>; - opacity?: ObjectOrArray; - radii?: ObjectOrArray>; - shadows?: ObjectOrArray; - textStyles?: ObjectOrArray; + borders?: ObjectOrArray> + buttons?: ObjectOrArray + colorStyles?: ObjectOrArray + fontWeights?: ObjectOrArray + fonts?: ObjectOrArray + heights?: ObjectOrArray> + letterSpacings?: ObjectOrArray> + lineHeights?: ObjectOrArray> + maxHeights?: ObjectOrArray> + maxWidths?: ObjectOrArray> + minHeights?: ObjectOrArray> + minWidths?: ObjectOrArray> + opacity?: ObjectOrArray + radii?: ObjectOrArray> + shadows?: ObjectOrArray + textStyles?: ObjectOrArray } /** @@ -139,10 +142,10 @@ export interface FontSizeProps { * - And array values are converted into responsive values. * */ - fontSize?: ResponsiveValue>; + fontSize?: ResponsiveValue> } -export function fontSize(...args: any[]): any; +export function fontSize(...args: any[]): any /** * Color @@ -158,10 +161,10 @@ export interface TextColorProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/color) */ - color?: ResponsiveValue; + color?: ResponsiveValue } -export function textColor(...args: any[]): any; +export function textColor(...args: any[]): any export interface BgColorProps { /** @@ -173,22 +176,22 @@ export interface BgColorProps { * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) */ - bg?: ResponsiveValue>; + bg?: ResponsiveValue> } -export function bgColor(...args: any[]): any; +export function bgColor(...args: any[]): any export interface ColorProps extends TextColorProps, BgColorProps {} -export function color(...args: any[]): any; +export function color(...args: any[]): any /** * Typography */ export interface FontFamilyProps { - fontFamily?: ResponsiveValue; + fontFamily?: ResponsiveValue } -export function fontFamily(...args: any[]): any; +export function fontFamily(...args: any[]): any export interface TextAlignProps { /** @@ -196,10 +199,10 @@ export interface TextAlignProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) */ - textAlign?: ResponsiveValue; + textAlign?: ResponsiveValue } -export function textAlign(...args: any[]): any; +export function textAlign(...args: any[]): any export interface LineHeightProps { /** @@ -210,9 +213,9 @@ export interface LineHeightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) */ - lineHeight?: ResponsiveValue>; + lineHeight?: ResponsiveValue> } -export function lineHeight(...args: any[]): any; +export function lineHeight(...args: any[]): any export interface FontWeightProps { /** @@ -222,10 +225,10 @@ export interface FontWeightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) */ - fontWeight?: ResponsiveValue; + fontWeight?: ResponsiveValue } -export function fontWeight(...args: any[]): any; +export function fontWeight(...args: any[]): any export interface FontStyleProps { /** @@ -234,9 +237,9 @@ export interface FontStyleProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) */ - fontStyle?: ResponsiveValue; + fontStyle?: ResponsiveValue } -export function fontStyle(...args: any[]): any; +export function fontStyle(...args: any[]): any export interface LetterSpacingProps { /** @@ -244,9 +247,9 @@ export interface LetterSpacingProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) */ - letterSpacing?: ResponsiveValue>; + letterSpacing?: ResponsiveValue> } -export function letterSpacing(...args: any[]): any; +export function letterSpacing(...args: any[]): any /** * Layout @@ -260,10 +263,10 @@ export interface DisplayProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/display) */ - display?: ResponsiveValue; + display?: ResponsiveValue } -export function display(...args: any[]): any; +export function display(...args: any[]): any export interface MaxWidthProps { /** @@ -272,10 +275,10 @@ export interface MaxWidthProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width) */ - maxWidth?: ResponsiveValue>; + maxWidth?: ResponsiveValue> } -export function maxWidth(...args: any[]): any; +export function maxWidth(...args: any[]): any export interface MinWidthProps { /** @@ -284,10 +287,10 @@ export interface MinWidthProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) */ - minWidth?: ResponsiveValue>; + minWidth?: ResponsiveValue> } -export function minWidth(...args: any[]): any; +export function minWidth(...args: any[]): any export interface WidthProps { /** @@ -298,10 +301,10 @@ export interface WidthProps { * - String values are passed as raw CSS values. * - And arrays are converted to responsive width styles. */ - width?: ResponsiveValue>; + width?: ResponsiveValue> } -export function width(...args: any[]): any; +export function width(...args: any[]): any export interface MaxHeightProps { /** @@ -310,10 +313,10 @@ export interface MaxHeightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-height) */ - maxHeight?: ResponsiveValue>; + maxHeight?: ResponsiveValue> } -export function maxHeight(...args: any[]): any; +export function maxHeight(...args: any[]): any export interface MinHeightProps { /** @@ -322,10 +325,10 @@ export interface MinHeightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/display) */ - minHeight?: ResponsiveValue>; + minHeight?: ResponsiveValue> } -export function minHeight(...args: any[]): any; +export function minHeight(...args: any[]): any export interface HeightProps { /** @@ -334,37 +337,37 @@ export interface HeightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/height) */ - height?: ResponsiveValue>; + height?: ResponsiveValue> } -export function height(...args: any[]): any; +export function height(...args: any[]): any // TODO: Document, I couldn't find any info on these two properties... export interface SizeWidthProps { - size?: ResponsiveValue>; + size?: ResponsiveValue> } -export function sizeWidth(...args: any[]): any; +export function sizeWidth(...args: any[]): any export interface SizeHeightProps { - size?: ResponsiveValue>; + size?: ResponsiveValue> } -export function sizeHeight(...args: any[]): any; +export function sizeHeight(...args: any[]): any export interface SizeProps extends SizeHeightProps, SizeWidthProps {} -export function size(...args: any[]): any; +export function size(...args: any[]): any export interface RatioProps { /** * The ration is height: 0 & paddingBottom */ - ratio?: ResponsiveValue; + ratio?: ResponsiveValue } -export function ratio(...args: any[]): any; +export function ratio(...args: any[]): any export interface VerticalAlignProps { /** @@ -372,10 +375,10 @@ export interface VerticalAlignProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) */ - verticalAlign?: ResponsiveValue>; + verticalAlign?: ResponsiveValue> } -export function verticalAlign(...args: any[]): any; +export function verticalAlign(...args: any[]): any /** * Flexbox @@ -391,10 +394,10 @@ export interface AlignItemsProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) */ - alignItems?: ResponsiveValue; + alignItems?: ResponsiveValue } -export function alignItems(...args: any[]): any; +export function alignItems(...args: any[]): any export interface AlignContentProps { /** @@ -403,10 +406,10 @@ export interface AlignContentProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content) */ - alignContent?: ResponsiveValue; + alignContent?: ResponsiveValue } -export function alignContent(...args: any[]): any; +export function alignContent(...args: any[]): any export interface JustifyItemsProps { /** @@ -415,7 +418,7 @@ export interface JustifyItemsProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items) */ - justifyItems?: ResponsiveValue; + justifyItems?: ResponsiveValue } export interface JustifyContentProps { @@ -425,10 +428,10 @@ export interface JustifyContentProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) */ - justifyContent?: ResponsiveValue; + justifyContent?: ResponsiveValue } -export function justifyContent(...args: any[]): any; +export function justifyContent(...args: any[]): any export interface FlexWrapProps { /** @@ -437,20 +440,20 @@ export interface FlexWrapProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap) */ - flexWrap?: ResponsiveValue; + flexWrap?: ResponsiveValue } -export function flexWrap(...args: any[]): any; +export function flexWrap(...args: any[]): any 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?: ResponsiveValue>; + flexBasis?: ResponsiveValue> } -export function flexBasis(...args: any[]): any; +export function flexBasis(...args: any[]): any export interface FlexDirectionProps { /** @@ -459,10 +462,10 @@ export interface FlexDirectionProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction) */ - flexDirection?: ResponsiveValue; + flexDirection?: ResponsiveValue } -export function flexDirection(...args: any[]): any; +export function flexDirection(...args: any[]): any export interface FlexProps { /** @@ -471,10 +474,10 @@ export interface FlexProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) */ - flex?: ResponsiveValue>; + flex?: ResponsiveValue> } -export function flex(...args: any[]): any; +export function flex(...args: any[]): any export interface JustifySelfProps { /** @@ -483,10 +486,10 @@ export interface JustifySelfProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self) */ - justifySelf?: ResponsiveValue; + justifySelf?: ResponsiveValue } -export function justifySelf(...args: any[]): any; +export function justifySelf(...args: any[]): any export interface AlignSelfProps { /** @@ -497,10 +500,10 @@ export interface AlignSelfProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) */ - alignSelf?: ResponsiveValue; + alignSelf?: ResponsiveValue } -export function alignSelf(...args: any[]): any; +export function alignSelf(...args: any[]): any export interface OrderProps { /** @@ -509,10 +512,10 @@ export interface OrderProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/order) */ - order?: ResponsiveValue; + order?: ResponsiveValue } -export function order(...args: any[]): any; +export function order(...args: any[]): any /** * Grid Layout @@ -527,10 +530,10 @@ export interface GridGapProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/gap) */ - gridGap?: ResponsiveValue>; + gridGap?: ResponsiveValue> } -export function gridGap(...args: any[]): any; +export function gridGap(...args: any[]): any export interface GridColumnGapProps { /** @@ -540,10 +543,10 @@ export interface GridColumnGapProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap) */ - gridColumnGap?: ResponsiveValue>; + gridColumnGap?: ResponsiveValue> } -export function gridColumnGap(...args: any[]): any; +export function gridColumnGap(...args: any[]): any export interface GridRowGapProps { /** @@ -553,10 +556,10 @@ export interface GridRowGapProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/row-gap) */ - gridRowGap?: ResponsiveValue>; + gridRowGap?: ResponsiveValue> } -export function gridRowGap(...args: any[]): any; +export function gridRowGap(...args: any[]): any export interface GridColumnProps { /** @@ -566,10 +569,10 @@ export interface GridColumnProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column) */ - gridColumn?: ResponsiveValue; + gridColumn?: ResponsiveValue } -export function gridColumn(...args: any[]): any; +export function gridColumn(...args: any[]): any export interface GridRowProps { /** @@ -579,10 +582,10 @@ export interface GridRowProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row) */ - gridRow?: ResponsiveValue; + gridRow?: ResponsiveValue } -export function gridRow(...args: any[]): any; +export function gridRow(...args: any[]): any export interface GridAutoFlowProps { /** @@ -591,10 +594,10 @@ export interface GridAutoFlowProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow) */ - gridAutoFlow?: ResponsiveValue; + gridAutoFlow?: ResponsiveValue } -export function gridAutoFlow(...args: any[]): any; +export function gridAutoFlow(...args: any[]): any export interface GridAutoColumnsProps { /** @@ -602,10 +605,10 @@ export interface GridAutoColumnsProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns) */ - gridAutoColumns?: ResponsiveValue>; + gridAutoColumns?: ResponsiveValue> } -export function gridAutoColumns(...args: any[]): any; +export function gridAutoColumns(...args: any[]): any export interface GridAutoRowsProps { /** @@ -613,10 +616,10 @@ export interface GridAutoRowsProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-rows) */ - gridAutoRows?: ResponsiveValue>; + gridAutoRows?: ResponsiveValue> } -export function gridAutoRows(...args: any[]): any; +export function gridAutoRows(...args: any[]): any export interface GridTemplatesColumnsProps { /** @@ -626,10 +629,10 @@ export interface GridTemplatesColumnsProps { */ gridTemplateColumns?: ResponsiveValue< CSS.GridTemplateColumnsProperty - >; + > } -export function gridTemplateColumns(...args: any[]): any; +export function gridTemplateColumns(...args: any[]): any export interface GridTemplatesRowsProps { /** @@ -637,10 +640,10 @@ export interface GridTemplatesRowsProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/row-template-rows) */ - gridTemplateRows?: ResponsiveValue>; + gridTemplateRows?: ResponsiveValue> } -export function gridTemplateRows(...args: any[]): any; +export function gridTemplateRows(...args: any[]): any export interface GridTemplatesAreasProps { /** @@ -648,10 +651,10 @@ export interface GridTemplatesAreasProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas) */ - gridTemplateAreas?: ResponsiveValue; + gridTemplateAreas?: ResponsiveValue } -export function gridTemplateAreas(...args: any[]): any; +export function gridTemplateAreas(...args: any[]): any export interface GridAreaProps { /** @@ -661,10 +664,10 @@ export interface GridAreaProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area) */ - gridArea?: ResponsiveValue; + gridArea?: ResponsiveValue } -export function gridArea(...args: any[]): any; +export function gridArea(...args: any[]): any /** * Borders @@ -677,10 +680,10 @@ export interface BorderProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border) */ - border?: ResponsiveValue>; + border?: ResponsiveValue> } -export function border(...args: any[]): any; +export function border(...args: any[]): any export interface BorderTopProps { /** @@ -689,10 +692,10 @@ export interface BorderTopProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top) */ - borderTop?: ResponsiveValue>; + borderTop?: ResponsiveValue> } -export function borderTop(...args: any[]): any; +export function borderTop(...args: any[]): any export interface BorderRightProps { /** @@ -701,10 +704,10 @@ export interface BorderRightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right) */ - borderRight?: ResponsiveValue>; + borderRight?: ResponsiveValue> } -export function borderRight(...args: any[]): any; +export function borderRight(...args: any[]): any export interface BorderBottomProps { /** @@ -713,10 +716,10 @@ export interface BorderBottomProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom) */ - borderBottom?: ResponsiveValue>; + borderBottom?: ResponsiveValue> } -export function borderBottom(...args: any[]): any; +export function borderBottom(...args: any[]): any export interface BorderLeftProps { /** @@ -725,10 +728,10 @@ export interface BorderLeftProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left) */ - borderLeft?: ResponsiveValue>; + borderLeft?: ResponsiveValue> } -export function borderLeft(...args: any[]): any; +export function borderLeft(...args: any[]): any export interface BordersProps extends BorderTopProps, @@ -736,7 +739,7 @@ export interface BordersProps BorderBottomProps, BorderLeftProps {} -export function borders(...args: any[]): any; +export function borders(...args: any[]): any export interface BorderColorProps { /** @@ -744,10 +747,10 @@ export interface BorderColorProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-color) */ - borderColor?: ResponsiveValue; + borderColor?: ResponsiveValue } -export function borderColor(...args: any[]): any; +export function borderColor(...args: any[]): any export interface BorderRadiusProps { /** @@ -756,10 +759,10 @@ export interface BorderRadiusProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) */ - borderRadius?: ResponsiveValue>; + borderRadius?: ResponsiveValue> } -export function borderRadius(...args: any[]): any; +export function borderRadius(...args: any[]): any export interface BoxShadowProps { /** @@ -769,10 +772,10 @@ export interface BoxShadowProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) */ - boxShadow?: ResponsiveValue; + boxShadow?: ResponsiveValue } -export function boxShadow(...arg: any[]): any; +export function boxShadow(...arg: any[]): any export interface OpacityProps { /** @@ -781,10 +784,10 @@ export interface OpacityProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) */ - opacity?: ResponsiveValue; + opacity?: ResponsiveValue } -export function opacity(...arg: any[]): any; +export function opacity(...arg: any[]): any export interface OverflowProps { /** @@ -793,10 +796,10 @@ export interface OverflowProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) */ - overflow?: ResponsiveValue; + overflow?: ResponsiveValue } -export function overflow(...arg: any[]): any; +export function overflow(...arg: any[]): any /** * Background */ @@ -808,10 +811,10 @@ export interface BackgroundProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background) */ - background?: ResponsiveValue>; + background?: ResponsiveValue> } -export function background(...args: any[]): any; +export function background(...args: any[]): any export interface BackgroundImageProps { /** @@ -819,10 +822,10 @@ export interface BackgroundImageProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) */ - backgroundImage?: ResponsiveValue; + backgroundImage?: ResponsiveValue } -export function backgroundImage(...args: any[]): any; +export function backgroundImage(...args: any[]): any export interface BackgroundSizeProps { /** @@ -831,10 +834,10 @@ export interface BackgroundSizeProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size) */ - backgroundSize?: ResponsiveValue>; + backgroundSize?: ResponsiveValue> } -export function backgroundSize(...args: any[]): any; +export function backgroundSize(...args: any[]): any export interface BackgroundPositionProps { /** @@ -845,10 +848,10 @@ export interface BackgroundPositionProps { */ backgroundPosition?: ResponsiveValue< CSS.BackgroundPositionProperty - >; + > } -export function backgroundPosition(...args: any[]): any; +export function backgroundPosition(...args: any[]): any export interface BackgroundRepeatProps { /** @@ -857,10 +860,10 @@ export interface BackgroundRepeatProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat) */ - backgroundRepeat?: ResponsiveValue; + backgroundRepeat?: ResponsiveValue } -export function backgroundRepeat(...args: any[]): any; +export function backgroundRepeat(...args: any[]): any /** * Position @@ -873,10 +876,10 @@ export interface PositionProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/position) */ - position?: ResponsiveValue; + position?: ResponsiveValue } -export function position(...args: any[]): any; +export function position(...args: any[]): any export interface ZIndexProps { /** @@ -885,10 +888,10 @@ export interface ZIndexProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/z-index) */ - zIndex?: ResponsiveValue; + zIndex?: ResponsiveValue } -export function zIndex(...args: any[]): any; +export function zIndex(...args: any[]): any export interface TopProps { /** @@ -897,10 +900,10 @@ export interface TopProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/top) */ - top?: ResponsiveValue>; + top?: ResponsiveValue> } -export function top(...args: any[]): any; +export function top(...args: any[]): any export interface RightProps { /** @@ -909,10 +912,10 @@ export interface RightProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/right) */ - right?: ResponsiveValue>; + right?: ResponsiveValue> } -export function right(...args: any[]): any; +export function right(...args: any[]): any export interface BottomProps { /** @@ -921,10 +924,10 @@ export interface BottomProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/top) */ - bottom?: ResponsiveValue>; + bottom?: ResponsiveValue> } -export function bottom(...args: any[]): any; +export function bottom(...args: any[]): any export interface LeftProps { /** @@ -933,33 +936,33 @@ export interface LeftProps { * * [MDN reference](https://developer.mozilla.org/en-US/docs/Web/CSS/left) */ - left?: ResponsiveValue>; + left?: ResponsiveValue> } -export function left(...args: any[]): any; +export function left(...args: any[]): any export interface TextStyleProps { - textStyle?: ResponsiveValue; + textStyle?: ResponsiveValue } -export function textStyle(...args: any[]): any; +export function textStyle(...args: any[]): any export interface ColorStyleProps { - colors?: ResponsiveValue; + colors?: ResponsiveValue } -export function colorStyle(...args: any[]): any; +export function colorStyle(...args: any[]): any export interface ButtonStyleProps { - variant?: ResponsiveValue; + variant?: ResponsiveValue } -export function buttonStyle(...args: any[]): any; +export function buttonStyle(...args: any[]): any export interface MixedProps { - key?: any; + key?: any // Defaults to "variant" - prop?: string; + prop?: string } -export function mixed(...args: any[]): any; +export function mixed(...args: any[]): any From b1ffb3b01f5a0703616c03b8dba7bb9e6e2ce77b Mon Sep 17 00:00:00 2001 From: gretzky Date: Thu, 31 Jan 2019 10:17:48 -0500 Subject: [PATCH 266/312] [styled-system] add object type to breakpoints --- types/styled-system/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 1207718523..67f1f87ba0 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -103,7 +103,7 @@ export function variant(props: VariantArgs): (...args: any[]) => any export type ObjectOrArray = T[] | { [K: string]: T } export interface BaseTheme { - breakpoints?: string[] + breakpoints?: string[] | Object colors?: ObjectOrArray fontSizes?: number[] space?: number[] From 83accda4872dbbbc6744be7211d74f959c290a71 Mon Sep 17 00:00:00 2001 From: gretzky Date: Thu, 31 Jan 2019 10:18:53 -0500 Subject: [PATCH 267/312] [styled-system] re-add number[] for posterity --- types/styled-system/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 67f1f87ba0..e2cdd2cddf 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -103,7 +103,7 @@ export function variant(props: VariantArgs): (...args: any[]) => any export type ObjectOrArray = T[] | { [K: string]: T } export interface BaseTheme { - breakpoints?: string[] | Object + breakpoints?: string[] | number[] | Object colors?: ObjectOrArray fontSizes?: number[] space?: number[] From d65aee88646ba3d9bec5c560f0e9c997624baa73 Mon Sep 17 00:00:00 2001 From: gretzky Date: Thu, 31 Jan 2019 10:20:44 -0500 Subject: [PATCH 268/312] [styled-system] increment version number --- types/styled-system/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index e2cdd2cddf..0efa5212fc 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.1 +// Type definitions for styled-system 3.2 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers // Ben McCormick From e7bf02f9438a411536654b21b34bd4ae9f44b8db Mon Sep 17 00:00:00 2001 From: Spencer Elliott Date: Thu, 31 Jan 2019 10:26:00 -0500 Subject: [PATCH 269/312] Use an array of React nodes for Next.js Document.getInitialProps().styles This `styles` property is always an array. See: https://github.com/zeit/next.js/blob/3a059688a8a0e10342ce697c89a7faebbeca9629/server/document.js#L18 https://www.npmjs.com/package/styled-jsx#styled-jsxserver --- types/next/document.d.ts | 2 +- types/next/test/next-document-tests.tsx | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 9ac8985cdf..e0879e1c68 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -37,7 +37,7 @@ export interface NextDocumentContext exte * https://github.com/zeit/next.js/blob/7.0.0/server/document.js#L16 */ export interface DefaultDocumentIProps extends RenderPageResponse { - styles?: React.ReactNode; + styles?: React.ReactNode[]; } /** diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index bf7ccf036d..83d0a0e8a3 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -35,7 +35,9 @@ class MyDocumentDefault extends Document { } class MyDoc extends Document { - static getInitialProps({ req, renderPage }: NextDocumentContext) { + static async getInitialProps(ctx: NextDocumentContext) { + const { req, renderPage } = ctx; + // without callback const _page = renderPage(); @@ -43,7 +45,9 @@ class MyDoc extends Document { const enhancer: Enhancer = App => props => ; const { html, head, buildManifest } = renderPage(enhancer); - const styles = [