From bd0de57f3c3ace8d08f5ccc5b89ef5ae1966922c Mon Sep 17 00:00:00 2001 From: Ron Zeidman Date: Mon, 10 Oct 2016 16:02:41 +0300 Subject: [PATCH 001/131] Error object fix Source: https://github.com/hapijs/joi/blob/master/API.md#errors ## Errors Joi throws classical javascript `Error`s containing : - `name` - `'ValidationError'`. - `isJoi` - `true`. - `details` - an array of errors : - `message` - string with a description of the error. - `path` - dotted path to the key where the error happened. - `type` - type of the error. - `context` - object providing context of the error. - `annotate` - function that returns a string with an annotated version of the object pointing at the places where errors occured. - `_object` - the original object to validate. --- joi/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/joi/index.d.ts b/joi/index.d.ts index ece6bb6d62..0b2cf1e8cb 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -121,17 +121,17 @@ export interface IPOptions { } export interface ValidationError extends Error { - message: string; + isJoi: boolean; details: ValidationErrorItem[]; - simple(): string; - annotated(): string; + annotate(): string; + _object: any; } export interface ValidationErrorItem { message: string; type: string; path: string; - options?: ValidationOptions; + context?: any; } export interface ValidationResult { From db86a7a621d9fe465f433ab6cf89e91952ff1d32 Mon Sep 17 00:00:00 2001 From: Ron Zeidman Date: Mon, 10 Oct 2016 16:05:26 +0300 Subject: [PATCH 002/131] Update joi-tests.ts --- joi/joi-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index eb0f147f78..557146cabc 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -125,7 +125,7 @@ validErrItem = { message: str, type: str, path: str, - options: validOpts + context: obj }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- From f116c1260178815885ad43ff7497f91abfb1fbc8 Mon Sep 17 00:00:00 2001 From: Ron Zeidman Date: Tue, 11 Oct 2016 09:47:42 +0300 Subject: [PATCH 003/131] Update index.d.ts Options does exist --- joi/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/joi/index.d.ts b/joi/index.d.ts index 0b2cf1e8cb..c192f49dd1 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -131,6 +131,7 @@ export interface ValidationErrorItem { message: string; type: string; path: string; + options?: ValidationOptions; context?: any; } From a388c6c5f9de3a3ba8afdf866a69e35e6ff44de2 Mon Sep 17 00:00:00 2001 From: Ron Zeidman Date: Tue, 11 Oct 2016 09:50:15 +0300 Subject: [PATCH 004/131] Update joi-tests.ts options does exist --- joi/joi-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 557146cabc..759be529ad 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -125,6 +125,7 @@ validErrItem = { message: str, type: str, path: str, + options: validOpts, context: obj }; From 76d8d5f439ea7ad02e5980950c0efc004bc9034e Mon Sep 17 00:00:00 2001 From: Joakim Gunst Date: Thu, 13 Oct 2016 12:26:36 +0300 Subject: [PATCH 005/131] Fixed bugs in angular-permission 2.3.6 type defintions. --- angular-permission/index.d.ts | 45 +++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/angular-permission/index.d.ts b/angular-permission/index.d.ts index 0b8d06f32a..8c03a79642 100644 --- a/angular-permission/index.d.ts +++ b/angular-permission/index.d.ts @@ -30,8 +30,8 @@ declare module 'angular' { * @param validationFunction {Function} Function used to validate if permission is valid */ definePermission( - name: string, - validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + permissionName: string, + validationFunction: PermissionValidationFunction ): void; /** @@ -43,10 +43,14 @@ declare module 'angular' { * @param validationFunction {Function} Function used to validate if permission is valid */ defineManyPermissions( - permissions: string[], - validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + permissionNames: string[], + validationFunction: PermissionValidationFunction ): void; + /** + * Removes all permissions + * @method + */ clearStore(): void; /** @@ -55,7 +59,7 @@ declare module 'angular' { * * @param permissionName {String} Name of defined permission */ - removePermissionDefinition(permission: string): void; + removePermissionDefinition(permissionName: string): void; /** * Checks if permission exists @@ -66,13 +70,21 @@ declare module 'angular' { */ hasPermissionDefinition(permissionName: string): boolean; + /** + * Returns permission by it's name + * @method + * + * @returns {permission.Permission} Permissions definition object + */ + getPermissionDefinition(permissionName: string): Permission; + /** * Returns all permissions * @method * * @returns {Object} Permissions collection */ - getStore(): Permission[]; + getStore(): {[permissionName: string]: Permission}; } export interface RoleStore { @@ -85,8 +97,8 @@ declare module 'angular' { * @param [validationFunction] {Function} Function used to validate if permissions in role are valid */ defineRole( - role: string, - permissions: Array, + roleName: string, + permissions: string[], validationFunction: RoleValidationFunction ): void; @@ -97,7 +109,10 @@ declare module 'angular' { * @param roleName {String} Name of defined role * @param permissions {Array} Set of permission names */ - defineRole(role: string, permissions: Array): void; + defineRole( + roleName: string, + permissions: string[] + ): void; /** * Checks if role is defined in store @@ -106,7 +121,7 @@ declare module 'angular' { * @param roleName {String} Name of role * @returns {Boolean} */ - hasRoleDefinition(role: string): boolean; + hasRoleDefinition(roleName: string): boolean; /** * Returns role definition object by it's name @@ -136,7 +151,7 @@ declare module 'angular' { * * @returns {Object} Defined roles collection */ - getStore(): Role[]; + getStore(): {[roleName: string]: Role}; } export interface Role { @@ -150,12 +165,12 @@ declare module 'angular' { validationFunction?: PermissionValidationFunction; } - interface RoleValidationFunction { - (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; + export interface RoleValidationFunction { + (roleName?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; } - interface PermissionValidationFunction { - (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; + export interface PermissionValidationFunction { + (permissionName?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; } export interface IPermissionState extends angular.ui.IState { From 5cd9600ed26230241d177b557bf558e232c1112b Mon Sep 17 00:00:00 2001 From: Joakim Gunst Date: Thu, 13 Oct 2016 14:28:41 +0300 Subject: [PATCH 006/131] Updated tests. --- angular-permission/angular-permission-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index 4f3a35f5df..051ace69b8 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -66,7 +66,7 @@ angular PermissionStore.removePermissionDefinition('user'); - let permissions: Array = PermissionStore.getStore(); + let permissions = PermissionStore.getStore(); }); @@ -90,5 +90,5 @@ angular RoleStore.removeRoleDefinition('user'); - let roles: Array = RoleStore.getStore(); + let roles = RoleStore.getStore(); }); From 76c4a34b96dbf795207dc132b1725cc95463c1ee Mon Sep 17 00:00:00 2001 From: Joakim Gunst Date: Thu, 13 Oct 2016 17:12:14 +0300 Subject: [PATCH 007/131] Removed redeclared 'cache' variable in 'ejs' that caused tests to fail. --- ejs/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/ejs/index.d.ts b/ejs/index.d.ts index b0f4bfeaa3..9f617287b7 100644 --- a/ejs/index.d.ts +++ b/ejs/index.d.ts @@ -62,7 +62,6 @@ declare namespace Ejs { set(key: string, val: any): any; get(key: string): any; } - var cache: Cache; function resolve(from1: string, to: string): string; function resolve(from1: string, from2: string, to: string): string; function resolve(from1: string, from2: string, from3: string, to: string): string; From 9b10e5ccd7aa30d89ed56a19d7c0d41893e6e13a Mon Sep 17 00:00:00 2001 From: Joakim Gunst Date: Fri, 14 Oct 2016 08:21:44 +0300 Subject: [PATCH 008/131] Fixes and improvements to angular-permission. --- angular-permission/index.d.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/angular-permission/index.d.ts b/angular-permission/index.d.ts index 8c03a79642..5d4b7f74c8 100644 --- a/angular-permission/index.d.ts +++ b/angular-permission/index.d.ts @@ -84,7 +84,7 @@ declare module 'angular' { * * @returns {Object} Permissions collection */ - getStore(): {[permissionName: string]: Permission}; + getStore(): { [permissionName: string]: Permission }; } export interface RoleStore { @@ -110,7 +110,7 @@ declare module 'angular' { * @param permissions {Array} Set of permission names */ defineRole( - roleName: string, + roleName: string, permissions: string[] ): void; @@ -151,7 +151,7 @@ declare module 'angular' { * * @returns {Object} Defined roles collection */ - getStore(): {[roleName: string]: Role}; + getStore(): { [roleName: string]: Role }; } export interface Role { @@ -165,13 +165,15 @@ declare module 'angular' { validationFunction?: PermissionValidationFunction; } - export interface RoleValidationFunction { - (roleName?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; - } + export type RoleValidationFunction = ( + roleName?: string, + transitionProperties?: TransitionProperties + ) => boolean | angular.IPromise; - export interface PermissionValidationFunction { - (permissionName?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; - } + export type PermissionValidationFunction = ( + permissionName?: string, + transitionProperties?: TransitionProperties + ) => boolean | angular.IPromise; export interface IPermissionState extends angular.ui.IState { data?: any | DataWithPermissions; @@ -179,8 +181,8 @@ declare module 'angular' { export interface DataWithPermissions { permissions?: { - only?: (() => void) | Array | angular.IPromise; - except?: (() => void) | Array | angular.IPromise; + only?: (() => void) | string | string[] | angular.IPromise; + except?: (() => void) | string | string[] | angular.IPromise; redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | { [index: string]: PermissionRedirectConfigation } }; } From 12f1b0a5571004f91b79a0d9c0aeb51957db92b4 Mon Sep 17 00:00:00 2001 From: Joakim Gunst Date: Fri, 14 Oct 2016 11:07:18 +0300 Subject: [PATCH 009/131] Added validate methods to Role and Permission in angular-permission. --- angular-permission/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/angular-permission/index.d.ts b/angular-permission/index.d.ts index 5d4b7f74c8..28781cb5df 100644 --- a/angular-permission/index.d.ts +++ b/angular-permission/index.d.ts @@ -158,11 +158,13 @@ declare module 'angular' { roleName: string; permissionNames: string[]; validationFunction?: RoleValidationFunction; + validateRole: () => angular.IPromise; } export interface Permission { permissionName: string; validationFunction?: PermissionValidationFunction; + validatePermission: () => angular.IPromise; } export type RoleValidationFunction = ( From 9f9210d7af2ebe1356fee4f16b8807af364a00e1 Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Wed, 19 Oct 2016 16:04:00 +0200 Subject: [PATCH 010/131] Fixed types for ora v0.3.0 --- ora/index.d.ts | 52 +++++++++++++++++++++++++++++------------------- ora/ora-tests.ts | 3 +-- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/ora/index.d.ts b/ora/index.d.ts index e58b5575c7..f5db7383e7 100644 --- a/ora/index.d.ts +++ b/ora/index.d.ts @@ -1,25 +1,37 @@ -// Type definitions for ora +// Type definitions for ora v0.3.0 // Project: https://github.com/sindresorhus/ora -// Definitions by: Basarat Ali Syed +// Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// -type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; -type Text = string; -interface Options { - text?: Text; - spinner?: string | { interval?: number; frames: string[]; } - color?: Color; - stream?: any; +declare module "ora" { + type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; + type Text = string; + interface Options { + text?: Text; + spinner?: string | Spinner; + color?: Color; + interval?: number; + stream?: NodeJS.WritableStream; + enabled?: boolean; + } + interface Spinner { + interval?: number; + frames: string[]; + } + interface Instance { + start(): Instance; + stop(): Instance; + succeed(): Instance; + fail(): Instance; + stopAndPersist(symbol?: string): Instance; + clear(): Instance; + render(): Instance; + frame(): Instance; + text: string; + color: Color; + } + function ora(options: Options | Text): Instance; + export = ora; } -interface Instance { - start(): void; - stop(): void; - clear(): void; - frame(): void; - render(): void; - text: Text; - color: Color; -} -declare function ora(options: Options | Text): Instance; -export = ora; diff --git a/ora/ora-tests.ts b/ora/ora-tests.ts index 7116db78ce..32e39aa753 100644 --- a/ora/ora-tests.ts +++ b/ora/ora-tests.ts @@ -1,8 +1,7 @@ import ora = require('ora'); -const spinner = ora('Loading unicorns'); -spinner.start(); +const spinner = ora('Loading unicorns').start(); setTimeout(() => { spinner.color = 'yellow'; From f572efa5593cb23f4f0003ec811b62a0d36a240c Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Thu, 20 Oct 2016 06:48:41 +0200 Subject: [PATCH 011/131] Fixed names in // Definitions --- ora/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ora/index.d.ts b/ora/index.d.ts index f5db7383e7..6e06bd35ec 100644 --- a/ora/index.d.ts +++ b/ora/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for ora v0.3.0 // Project: https://github.com/sindresorhus/ora -// Definitions by: Christian Rackerseder +// Definitions by: Basarat Ali Syed , Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 5d4a5b426e4fc57bf357089c8154e00969edef64 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Oct 2016 01:27:57 -0700 Subject: [PATCH 012/131] Added type declarations for 'vivus'. --- vivus/index-tests.ts | 85 ++++++++++++++++++++++++++++ vivus/index.d.ts | 132 +++++++++++++++++++++++++++++++++++++++++++ vivus/tsconfig.json | 15 +++++ 3 files changed, 232 insertions(+) create mode 100644 vivus/index-tests.ts create mode 100644 vivus/index.d.ts create mode 100644 vivus/tsconfig.json diff --git a/vivus/index-tests.ts b/vivus/index-tests.ts new file mode 100644 index 0000000000..aefe0109ee --- /dev/null +++ b/vivus/index-tests.ts @@ -0,0 +1,85 @@ +import Vivus = require("vivus"); + +function assertNever(input: never) { + throw new Error("Should never get here!"); +} + +function onEndOfAnimation(v: Vivus) { + v = v.play(0.5).stop(); + + const status = v.getStatus(); + switch (status) { + case "start": + case "progress": + case "end": + break; + default: + assertNever(status); + } + + v.setFrameProgress(0.5).play().reset().finish().destroy(); +} + +// Documentation tests. + +new Vivus("my-svg", { duration: 200 }, onEndOfAnimation); + +new Vivus("my-div", { duration: 200, file: "link/to/my.svg" }, onEndOfAnimation); + +var myVivus = new Vivus("my-svg-element"); +myVivus.stop().reset().play(2); + +new Vivus("my-svg-element", { + type: "delayed", + duration: 200, + animTimingFunction: Vivus.EASE +}, onEndOfAnimation); + + + +// Empty options tests. + +new Vivus("svg-element", {}); + +const el = document.getElementById("my-element") !; + +// 'duration' & 'delay' options tests. + +new Vivus(el, { duration: 200, delay: 199 }) + +// 'type' option tests. + +new Vivus(el, { type: "delayed" }); +new Vivus(el, { type: "async" }); +new Vivus(el, { type: "oneByOne" }); +new Vivus(el, { type: "script" }); + +// 'start' option tests. + +new Vivus(el, { start: "inViewport" }); +new Vivus(el, { start: "manual" }); +new Vivus(el, { start: "autostart" }); + +// Custom & built-in easing functions in options. + +new Vivus("my-svg-element", { + animTimingFunction: Vivus.EASE_OUT_BOUNCE, + pathTimingFunction: x => x ** 0.5, +}); + +function testEasingFunctions() { + var n: number; + + n = Vivus.LINEAR(0); + n = Vivus.LINEAR(1); + n = Vivus.EASE(0); + n = Vivus.EASE(1); + n = Vivus.EASE_IN(0); + n = Vivus.EASE_IN(1); + n = Vivus.EASE_OUT(0); + n = Vivus.EASE_OUT(1); + n = Vivus.EASE_OUT_BOUNCE(0); + n = Vivus.EASE_OUT_BOUNCE(1); + + return n; +} \ No newline at end of file diff --git a/vivus/index.d.ts b/vivus/index.d.ts new file mode 100644 index 0000000000..0c2f8b0ca5 --- /dev/null +++ b/vivus/index.d.ts @@ -0,0 +1,132 @@ +// Type definitions for Vivus 0.3.2 +// Project: http://maxwellito.github.io/vivus/ +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Vivus; +export as namespace Vivus; + +declare class Vivus { + static LINEAR: Vivus.TimingFunction; + static EASE: Vivus.TimingFunction; + static EASE_OUT: Vivus.TimingFunction; + static EASE_IN: Vivus.TimingFunction; + static EASE_OUT_BOUNCE: Vivus.TimingFunction; + + /** + * @param element The DOM element, or the ID of a DOM element, to interact with. + * @param options + * @param callback Callback to call at the end of the animation + */ + constructor(element: string | HTMLElement, options?: Vivus.VivusOptions, callback?: (vivusInstance: Vivus) => void); + + /** + * Plays the animation with the speed given in parameter. + * A speed of `1` is the normal speed. + * This value can be negative to go reverse, between 0 and 1 to play slowly, or greater than 1 to go faster. + * + * (default: `1`) + */ + play(speed?: number): this; + + /** + * Stops the animation. + */ + stop(): this; + + /** + * Reinitialises the SVG to the original undrawn state. + */ + reset(): this; + + /** + * Completely draws the SVG at its final state. + */ + finish(): this; + + /** + * Set the progress of the animation. + * Progress must be a `number` between `0` and `1`. + */ + setFrameProgress(progress: number): this; + + /** + * Get the status of the animation between start, progress, end. + */ + getStatus(): 'start' | 'progress' | 'end'; + + /** + * Reset the SVG but make the instance out of order. + */ + destroy(): void; +} + +declare namespace Vivus { + export type TimingFunction = (input: number) => number; + + export interface VivusOptions { + /** + * Determines if the item must be drawn asynchronously or not. + * Can be `'delayed'`, `'async'`, `'oneByOne'`, or `'script'`. + * (default: `'delayed'`) + */ + type?: 'delayed' | 'async' | 'oneByOne' | 'script'; + /** + * Link to the SVG to animate. + * If set, Vivus will create an object tag and append it to the DOM element given to the constructor. + * Be careful, use the `onReady` callback before playing with the Vivus instance. + */ + file?: string; + /** + * Animation duration, in frames. + * (default: `200`) + */ + duration?: number; + /** + * Automatically starts the animation. + * Can be `'inViewport'`, `'manual'`, or `'autostart'` + * (default: `'inViewport'`) + */ + start?: 'inViewport' | 'manual' | 'autostart'; + /** + * Time between the drawing of first and last path, in frames (only for `delayed` animations). + */ + delay?: number; + /** + * Function called when the instance is ready to play. + */ + onReady?: (vivusInstance: Vivus) => void; + /** + * Timing animation function for each path element of the SVG. + * It must accept a `number` as a parameter (between 0 to 1), and return a `number` (also between 0 and 1) as a result. + * + * See the [timing function documentation](https://github.com/maxwellito/vivus#timing-function). + */ + pathTimingFunction?: Vivus.TimingFunction; + /** + * Timing animation function for the complete SVG. + * It must accept a `number` as a parameter (between 0 to 1), and return a `number` (also between 0 and 1) as a result. + * + * See the [timing function documentation](https://github.com/maxwellito/vivus#timing-function). + */ + animTimingFunction?: Vivus.TimingFunction; + /** + * Whitespace extra margin between dashes. + * Increase it in case of glitches at the initial state of the animation. + * + * (default: `2`) + */ + dashGap?: number; + /** + * Force the browser to re-render all updated path items. + * By default, the value is `true` on IE only. + * + * See [the troubleshooting documentation for more details](https://github.com/maxwellito/vivus#troubleshoot). + */ + forceRender?: boolean; + /** + * Removes all extra styling on the SVG, and leaves it as original. + */ + selfDestroy?: boolean; + } +} diff --git a/vivus/tsconfig.json b/vivus/tsconfig.json new file mode 100644 index 0000000000..9cb518c427 --- /dev/null +++ b/vivus/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file From ae6c192dfe08d6ba5bd7c41d73d6e82ae573d4b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Guillot?= Date: Thu, 20 Oct 2016 11:56:54 +0200 Subject: [PATCH 013/131] Added shouldUpdatePosition prop in Overlay --- react-bootstrap/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index ab5b020bbf..4b85a40a27 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -428,6 +428,7 @@ declare namespace ReactBootstrap { rootClose?: boolean; show?: boolean; target?: Function; + shouldUpdatePosition?: boolean; } class Overlay extends React.Component { } From 56dd03b2f659df102383cd829be414545adf2ef0 Mon Sep 17 00:00:00 2001 From: rickydigime Date: Thu, 20 Oct 2016 13:53:47 +0100 Subject: [PATCH 014/131] Update index.d.ts bsStyle can be used on DropdownToggle too. --- react-bootstrap/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index ab5b020bbf..a37f10b4d3 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -206,6 +206,7 @@ declare namespace ReactBootstrap { title?: string; useAnchor?: boolean; bsClass?:string; // Added since v0.30.0 + bsStyle?:string; } class DropdownToggle extends React.Component { } From 38960a30f9516850dc78b3c1abbe33662ea72f79 Mon Sep 17 00:00:00 2001 From: feng zhi hao Date: Fri, 21 Oct 2016 16:43:35 +0800 Subject: [PATCH 015/131] add @types/history dependency --- react-router/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 8dfc205478..f3984853cd 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + export as namespace ReactRouter; import * as React from 'react'; From dff0f0f29c6485d98d3a9e1e75030e553832dce6 Mon Sep 17 00:00:00 2001 From: Hendrik Liebau Date: Mon, 24 Oct 2016 12:08:37 +0200 Subject: [PATCH 016/131] export ReactHelmet namespace --- react-helmet/index.d.ts | 11 +++++------ react-helmet/react-helmet-tests.tsx | 6 ++++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/react-helmet/index.d.ts b/react-helmet/index.d.ts index c44639e0d0..3ddfd1ebb5 100644 --- a/react-helmet/index.d.ts +++ b/react-helmet/index.d.ts @@ -7,14 +7,11 @@ import * as React from "react"; -declare var Helmet: { - (): ReactHelmet.HelmetComponent - rewind(): ReactHelmet.HelmetData - } - -export = Helmet; +declare function ReactHelmet(): ReactHelmet.HelmetComponent; declare namespace ReactHelmet { + function rewind(): ReactHelmet.HelmetData; + interface HelmetProps { base?: any; defaultTitle?: string; @@ -43,3 +40,5 @@ declare namespace ReactHelmet { class HelmetComponent extends React.Component {} } + +export = ReactHelmet; diff --git a/react-helmet/react-helmet-tests.tsx b/react-helmet/react-helmet-tests.tsx index 2db79eb547..3a4a3f09d7 100644 --- a/react-helmet/react-helmet-tests.tsx +++ b/react-helmet/react-helmet-tests.tsx @@ -39,3 +39,9 @@ function HTML() { ); } + +function log(datum: Helmet.HelmetDatum) { + return console.log('logging a helmet datum:', datum.toString()); +} + +log(head.title); From 14eed8a1fef49ef9543dd9a75a5622afb23ade30 Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Wed, 26 Oct 2016 07:34:34 +0200 Subject: [PATCH 017/131] Replaced Text with string --- ora/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ora/index.d.ts b/ora/index.d.ts index 6e06bd35ec..976005200b 100644 --- a/ora/index.d.ts +++ b/ora/index.d.ts @@ -7,9 +7,8 @@ declare module "ora" { type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; - type Text = string; interface Options { - text?: Text; + text?: string; spinner?: string | Spinner; color?: Color; interval?: number; @@ -32,6 +31,6 @@ declare module "ora" { text: string; color: Color; } - function ora(options: Options | Text): Instance; + function ora(options: Options | string): Instance; export = ora; } From a27693680c4fcde005f99ceeb2f4b1182c76ee7b Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Thu, 27 Oct 2016 11:21:39 +0200 Subject: [PATCH 018/131] Removed declare module "ora" --- ora/index.d.ts | 54 ++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/ora/index.d.ts b/ora/index.d.ts index 976005200b..e45a585442 100644 --- a/ora/index.d.ts +++ b/ora/index.d.ts @@ -5,32 +5,30 @@ /// -declare module "ora" { - type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; - interface Options { - text?: string; - spinner?: string | Spinner; - color?: Color; - interval?: number; - stream?: NodeJS.WritableStream; - enabled?: boolean; - } - interface Spinner { - interval?: number; - frames: string[]; - } - interface Instance { - start(): Instance; - stop(): Instance; - succeed(): Instance; - fail(): Instance; - stopAndPersist(symbol?: string): Instance; - clear(): Instance; - render(): Instance; - frame(): Instance; - text: string; - color: Color; - } - function ora(options: Options | string): Instance; - export = ora; +type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; +interface Options { + text?: string; + spinner?: string | Spinner; + color?: Color; + interval?: number; + stream?: NodeJS.WritableStream; + enabled?: boolean; } +interface Spinner { + interval?: number; + frames: string[]; +} +interface Instance { + start(): Instance; + stop(): Instance; + succeed(): Instance; + fail(): Instance; + stopAndPersist(symbol?: string): Instance; + clear(): Instance; + render(): Instance; + frame(): Instance; + text: string; + color: Color; +} +declare function ora(options: Options | string): Instance; +export = ora; From 737653ccb00bce0a39e2070a78a7105806ebd6f9 Mon Sep 17 00:00:00 2001 From: Casper Skydt Date: Fri, 28 Oct 2016 13:39:38 +0200 Subject: [PATCH 019/131] Added Kinises to AWS-SDK --- aws-sdk/aws-sdk-tests.ts | 39 ++++++++++++++++++++++++++++++ aws-sdk/index.d.ts | 52 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts index 7d3b7a5c2c..5188a3e725 100644 --- a/aws-sdk/aws-sdk-tests.ts +++ b/aws-sdk/aws-sdk-tests.ts @@ -381,3 +381,42 @@ dynamoDBDocClient.query( else console.log(data); // successful response } ); + +var kinesis = new AWS.Kinesis(); + +var putRecordParam = { + Data: new Buffer('...') || 'STRING_VALUE', /* required */ + PartitionKey: 'STRING_VALUE', /* required */ + StreamName: 'STRING_VALUE', /* required */ + ExplicitHashKey: 'STRING_VALUE', + SequenceNumberForOrdering: 'STRING_VALUE' +}; +kinesis.putRecord(putRecordParam, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); + +var putRecordParams = { + Records: [ /* required */ + { + Data: new Buffer('...') || 'STRING_VALUE', /* required */ + PartitionKey: 'STRING_VALUE', /* required */ + ExplicitHashKey: 'STRING_VALUE' + }, + /* more items */ + ], + StreamName: 'STRING_VALUE' /* required */ +}; +kinesis.putRecords(putRecordParams, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); + +var increaseStreamRetentionPeriodParams = { + RetentionPeriodHours: 0, /* required */ + StreamName: 'STRING_VALUE' /* required */ +}; +kinesis.increaseStreamRetentionPeriod(increaseStreamRetentionPeriodParams, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); \ No newline at end of file diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index 7d70edf939..42919b3d57 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for aws-sdk // Project: https://github.com/aws/aws-sdk-js -// Definitions by: midknight41 +// Definitions by: midknight41 , Casper Skydt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts @@ -335,6 +335,56 @@ export declare class SNS { publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; } +export class Kinesis { + constructor(options?: any); + endpoint: Endpoint; + + putRecord(params: KINESIS.PutRecordParams, callback: (error: Error, data: KINESIS.PutRecordResult) => void): void; + putRecords(params: KINESIS.PutRecordsParams, callback: (error: Error, data: KINESIS.PutRecordsResult) => void): void; + increaseStreamRetentionPeriod(params: KINESIS.IncreaseStreamRetentionPeriodParams, callback: (error: Error, data: any) => void): void; + } + + export module KINESIS { + export interface Record { + Data: Buffer | string | Blob; + PartitionKey: string; + ExplicitHashKey?: string; + } + + export interface RecordResult { + SequenceNumber: string; + ShardId: string; + ErrorCode: string; + ErrorMessage: string; + } + + export interface PutRecordParams extends Record { + StreamName: string; + SequenceNumberForOrdering?: string; + } + + export interface PutRecordResult { + ShardId: string; + SequenceNumber: string; + } + + export interface PutRecordsParams { + StreamName: string; + Records: Record[]; + } + + export interface PutRecordsResult { + FailedRecordCount: number; + Records: RecordResult[] + } + + export interface IncreaseStreamRetentionPeriodParams { + RetentionPeriodHours: number; + StreamName: string; + } + } + + export declare class SWF { constructor(options?: any); endpoint: Endpoint; From 07765863bfc72cfdb767bcc60997f8738fb00a8e Mon Sep 17 00:00:00 2001 From: hktonylee Date: Wed, 2 Nov 2016 21:18:52 +0800 Subject: [PATCH 020/131] added fetch function in react-native (#12408) --- react-native/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-native/index.d.ts b/react-native/index.d.ts index 9bd87c5013..8900ce0a0b 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -7569,6 +7569,7 @@ declare module "react" { // Network Polyfill // TODO: Add proper support for fetch export type fetch = (url: string, options?: Object) => Promise + export const fetch: fetch; // Timers polyfill export type timedScheduler = (fn: string | Function, time: number) => number From 1ebf11b4eb1010a6d3e2dd486f8fc9628573619a Mon Sep 17 00:00:00 2001 From: Melvin Groenhoff Date: Wed, 2 Nov 2016 14:21:44 +0100 Subject: [PATCH 021/131] ES6 typings contain responseURL. Fixes #12434. (#12435) --- chocolatechipjs/index.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/chocolatechipjs/index.d.ts b/chocolatechipjs/index.d.ts index 9ac2ae8c52..f1e0701e39 100644 --- a/chocolatechipjs/index.d.ts +++ b/chocolatechipjs/index.d.ts @@ -1359,10 +1359,6 @@ interface fetch { }): Promise; } -interface XMLHttpRequest { - responseURL: string; -} - /** * Headers Interface. This defines the methods exposed by the Headers object. */ From e88fdefc1776013ba142b97db3ee3385e73646b9 Mon Sep 17 00:00:00 2001 From: Borek Bernard Date: Wed, 2 Nov 2016 14:30:06 +0100 Subject: [PATCH 022/131] Add types for 'promisify-node' (#12386) * Added types for 'promisify-node' * Optional boolean param instead of default value --- promisify-node/index.d.ts | 17 +++++++++++++++++ promisify-node/promisify-node-tests.ts | 7 +++++++ promisify-node/tsconfig.json | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 promisify-node/index.d.ts create mode 100644 promisify-node/promisify-node-tests.ts create mode 100644 promisify-node/tsconfig.json diff --git a/promisify-node/index.d.ts b/promisify-node/index.d.ts new file mode 100644 index 0000000000..ed50550321 --- /dev/null +++ b/promisify-node/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for promisify-node 0.4.0 +// Project: https://github.com/nodegit/promisify-node +// Definitions by: Borek Bernard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +export = promisify; + +/** + * Public API for Promisify. Will resolve modules names using `require`. + * + * @param {*} name - Can be a module name, object, or function. + * @param {Function} test - Optional function to identify async methods. + * @param {Boolean} noMutate - Optional set to true to avoid mutating the target. + * @returns {*} exports - The resolved value from require or passed in value. + */ +declare function promisify(name: string | Object | Function, test?: Function, noMutate?: boolean): any; diff --git a/promisify-node/promisify-node-tests.ts b/promisify-node/promisify-node-tests.ts new file mode 100644 index 0000000000..2780e8775b --- /dev/null +++ b/promisify-node/promisify-node-tests.ts @@ -0,0 +1,7 @@ +import promisify = require('promisify-node'); + +let fs = promisify('fs'); + +fs.readFile('example.txt').then((content: any) => { + console.log(content); +}); diff --git a/promisify-node/tsconfig.json b/promisify-node/tsconfig.json new file mode 100644 index 0000000000..3ee5061fee --- /dev/null +++ b/promisify-node/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promisify-node-tests" + ] +} From f7e05529ff17d43ec73407d583e7aa1ce2431edb Mon Sep 17 00:00:00 2001 From: Franky Lau Date: Wed, 2 Nov 2016 21:36:37 +0800 Subject: [PATCH 023/131] Update node-forge (#12352) * Update 'node-forge' * Update indentation * Add test case * Remove unnecessary reference --- node-forge/index.d.ts | 253 +++++++++++++++++++++++++++++---- node-forge/node-forge-tests.ts | 73 +++++++++- 2 files changed, 295 insertions(+), 31 deletions(-) diff --git a/node-forge/index.d.ts b/node-forge/index.d.ts index b39ede7ac4..7e51f0689d 100644 --- a/node-forge/index.d.ts +++ b/node-forge/index.d.ts @@ -4,41 +4,234 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-forge" { + type Byte = string; + type Bytes = string; + type Hex = string; + type Base64 = string; + type Utf8 = string; + type OID = string; - export namespace pki { + namespace pki { - export type PEM = string; - export type Key = any; + type PEM = string; + type Key = any; - export interface KeyPair { - publicKey: Key; - privateKey: Key; + interface KeyPair { + publicKey: Key; + privateKey: Key; + } + + function privateKeyToPem(key: Key, maxline?: number): PEM; + function publicKeyToPem(key: Key, maxline?: number): PEM; + + interface oids { + [key: string]: string; + } + var oids: oids; + + namespace rsa { + + interface GenerateKeyPairOptions { + bits?: number; + e?: number; + workerScript?: string; + workers?: number; + workLoad?: number; + prng?: any; + algorithm?: string; + } + + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; + function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; + } + + interface CertificateFieldOptions { + name?: string; + type?: string; + shortName?: string; + } + + interface CertificateField extends CertificateFieldOptions { + valueConstructed?: boolean; + valueTagClass?: asn1.Class; + value?: any[]; + extensions?: any[]; + } + + interface Certificate { + version: number; + serialNumber: string; + signature: any; + siginfo: any; + validity: { + notBefore: Date; + notAfter: Date; + }; + issuer: { + getField(sn: string | CertificateFieldOptions): any; + addField(attr: CertificateField): void; + attributes: any[]; + hash: any; + }; + subject: { + getField(sn: string | CertificateFieldOptions): any; + addField(attr: CertificateField): void; + attributes: any[]; + hash: any; + }; + extensions: any[]; + publicKey: any; + md: any; + } + + function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; + + function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; } - export function privateKeyToPem(key: Key, maxline?: number): PEM; - export function publicKeyToPem(key: Key, maxline?: number): PEM; - - export namespace rsa { - - export interface GenerateKeyPairOptions { - bits?: number; - e?: number; - workerScript?: string; - workers?: number; - workLoad?: number; - prng?: any; - algorithm?: string; - } - - export function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; - export function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; + namespace ssh { + /** + * Encodes a private RSA key as an OpenSSH file. + */ + function privateKeyToOpenSSH(privateKey?: string, passphrase?: string): string; } - } - export namespace ssh { - /** - * Encodes a private RSA key as an OpenSSH file. - */ - export function privateKeyToOpenSSH(privateKey?: string, passphrase?: string): string; - } + namespace asn1 { + enum Class { + UNIVERSAL = 0x00, + APPLICATION = 0x40, + CONTEXT_SPECIFIC = 0x80, + PRIVATE = 0xC0, + } + + enum Type { + NONE = 0, + BOOLEAN = 1, + INTEGER = 2, + BITSTRING = 3, + OCTETSTRING = 4, + NULL = 5, + OID = 6, + ODESC = 7, + EXTERNAL = 8, + REAL = 9, + ENUMERATED = 10, + EMBEDDED = 11, + UTF8 = 12, + ROID = 13, + SEQUENCE = 16, + SET = 17, + PRINTABLESTRING = 19, + IA5STRING = 22, + UTCTIME = 23, + GENERALIZEDTIME = 24, + BMPSTRING = 30, + } + + interface Asn1 { + tagClass: Class; + type: Type; + constructed: boolean; + composed: boolean; + value: Asn1[]; + } + + function create(tagClass: Class, type: Type, constructed: boolean, value: string | Asn1[]): Asn1; + function fromDer(bytes: Bytes | util.ByteBuffer, strict?: boolean): Asn1; + function toDer(obj: Asn1): util.ByteBuffer; + function oidToDer(oid: OID): util.ByteStringBuffer; + function derToOid(der: util.ByteStringBuffer): OID; + } + + namespace util { + function isArray(x: any): boolean; + function isArrayBuffer(x: any): boolean; + function isArrayBufferView(x: any): boolean; + + interface ArrayBufferView { + buffer: ArrayBuffer; + byteLength: number; + } + + type ByteBuffer = ByteStringBuffer; + class ByteStringBuffer { + constructor(bytes?: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer); + data: string; + read: number; + length(): number; + isEmpty(): boolean; + putByte(byte: Byte): ByteStringBuffer; + fillWithByte(byte: Byte, n: number): ByteStringBuffer; + putBytes(bytes: Bytes): ByteStringBuffer; + putString(str: string): ByteStringBuffer; + putInt16(int: number): ByteStringBuffer; + putInt24(int: number): ByteStringBuffer; + putInt32(int: number): ByteStringBuffer; + putInt16Le(int: number): ByteStringBuffer; + putInt24Le(int: number): ByteStringBuffer; + putInt32Le(int: number): ByteStringBuffer; + putInt(int: number, numOfBits: number): ByteStringBuffer; + putSignedInt(int: number, numOfBits: number): ByteStringBuffer; + putBuffer(buffer: ByteStringBuffer): ByteStringBuffer; + getByte(): number; + getInt16(): number; + getInt24(): number; + getInt32(): number; + getInt16Le(): number; + getInt24Le(): number; + getInt32Le(): number; + getInt(numOfBits: number): number; + getSignedInt(numOfBits: number): number; + getBytes(count?: number): Bytes; + bytes(count?: number): Bytes; + at(index: number): Byte; + setAt(index: number, byte: number): ByteStringBuffer; + last(): Byte; + copy(): ByteStringBuffer; + compact(): ByteStringBuffer; + clear(): ByteStringBuffer; + truncate(): ByteStringBuffer; + toHex(): Hex; + toString(): string; + } + + function fillString(char: string, count: number): string; + function xorBytes(bytes1: string, bytes2: string, count: number): string; + function hexToBytes(hex: Hex): Bytes; + function bytesToHex(bytes: Bytes): Hex; + function int32ToBytes(int: number): Bytes; + function encode64(bytes: Bytes, maxline?: number): Base64; + function decode64(encoded: Base64): Bytes; + function encodeUtf8(str: string): Utf8; + function decodeUtf8(encoded: Utf8): string; + + function createBuffer(): ByteBuffer; + function createBuffer(input: string, encode: string): ByteBuffer; + + namespace binary { + namespace raw { + function encode(x: Uint8Array): Bytes; + function decode(str: Bytes, output?: Uint8Array, offset?: number): Uint8Array; + } + namespace hex { + function encode(bytes: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer): Hex; + function decode(hex: Hex, output?: Uint8Array, offset?: number): Uint8Array; + } + namespace base64 { + function encode(input: Uint8Array, maxline?: number): Base64; + function decode(input: Base64, output?: Uint8Array, offset?: number): Uint8Array; + } + } + + namespace text { + namespace utf8 { + function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array; + function decode(bytes: Uint8Array): Utf8; + } + namespace utf16 { + function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array; + function decode(bytes: Uint8Array): string; + } + } + } } diff --git a/node-forge/node-forge-tests.ts b/node-forge/node-forge-tests.ts index 7ed36e50e2..8865f6998f 100644 --- a/node-forge/node-forge-tests.ts +++ b/node-forge/node-forge-tests.ts @@ -3,5 +3,76 @@ import * as forge from "node-forge"; let keypair = forge.pki.rsa.generateKeyPair({bits: 512}); let privateKeyPem = forge.pki.privateKeyToPem(keypair.privateKey); let publicKeyPem = forge.pki.publicKeyToPem(keypair.publicKey); +let key = forge.pki.decryptRsaPrivateKey(privateKeyPem); +let x: string = forge.ssh.privateKeyToOpenSSH(key); -let x: string = forge.ssh.privateKeyToOpenSSH(); +{ + let subjectPublicKeyInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, + forge.asn1.oidToDer(forge.pki.oids['rsaEncryption']).getBytes(), + ), + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''), + ]), + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.BITSTRING, false, [ + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, []), + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, []), + ]) + ]) + ]); + let derBuffer = forge.asn1.toDer(subjectPublicKeyInfo); + let object = forge.asn1.fromDer(derBuffer); +} + +{ + let oidSrc = '1.2.840.113549.1.1.5'; + let derOidBuffer = forge.asn1.oidToDer(oidSrc); + let oidResult = forge.asn1.derToOid(derOidBuffer); + if(oidSrc !== oidResult) throw Error('forge.asn1.oidToDer / derToOid fail'); +} + +if(forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillString fail'); + +{ + let hex: string = '61'; + let bytes: string = forge.util.hexToBytes(hex); + let result: string = forge.util.bytesToHex(bytes); + if(bytes !== 'a' || result !== hex) throw Error('forge.util.hexToBytes / bytesToHex fail'); +} + +{ + let src: Uint8Array; + let encode: string; + let decode: Uint8Array; + + src = new Uint8Array(2); + encode = forge.util.binary.hex.encode(src); + decode = forge.util.binary.hex.decode(encode); + if(encode !== '0000' || src.byteLength !== decode.byteLength) throw Error('forge.util.binary.hex.encode / decode fail'); + + src = new Uint8Array(2); + encode = forge.util.binary.base64.encode(src); + decode = forge.util.binary.base64.decode(encode); + if(encode !== 'AAA=' || src.byteLength !== decode.byteLength) throw Error('forge.util.binary.base64.encode / decode fail'); + + src = new Uint8Array(10); + encode = forge.util.binary.raw.encode(src); + decode = forge.util.binary.raw.decode(encode); + if(src.byteLength !== decode.byteLength) throw Error('forge.util.binary.raw.encode / decode fail'); +} + +{ + let src: string; + let encode: Uint8Array; + let decode : string; + + src = 'Test'; + encode = forge.util.text.utf8.encode(src); + decode = forge.util.text.utf8.decode(encode); + if(src !== decode) throw Error('forge.util.text.utf8.encode / decode fail'); + src = 'Test'; + encode = forge.util.text.utf16.encode(src); + decode = forge.util.text.utf16.decode(encode); + if(src !== decode) throw Error('forge.util.text.utf8.encode / decode fail'); +} From f71bca5275190ca853505ce3bd2af7daf989d9e7 Mon Sep 17 00:00:00 2001 From: Jeffery Grajkowski Date: Wed, 2 Nov 2016 06:38:19 -0700 Subject: [PATCH 024/131] Updated yargs to 6.3.0 (#12356) * Updated yargs to 6.3.0 * Added more tests cases for yargs. Made a couple improvements to the typings in the process. --- yargs/index.d.ts | 50 +++++++++++++++++-------- yargs/yargs-tests.ts | 89 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 15 deletions(-) diff --git a/yargs/index.d.ts b/yargs/index.d.ts index 8f6f7cf531..238f5d1edd 100644 --- a/yargs/index.d.ts +++ b/yargs/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for yargs +// Type definitions for yargs 6.3.0 // Project: https://github.com/chevex/yargs -// Definitions by: Martin Poelstra , Mizunashi Mana +// Definitions by: Martin Poelstra , Mizunashi Mana , Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace yargs { @@ -18,12 +18,6 @@ declare namespace yargs { terminalWidth(): number; - terminalWidth(): number; - - terminalWidth(): number; - - terminalWidth(): number; - alias(shortName: string, longName: string): Argv; alias(aliases: { [shortName: string]: string }): Argv; alias(aliases: { [shortName: string]: string[] }): Argv; @@ -31,8 +25,8 @@ declare namespace yargs { array(key: string): Argv; array(keys: string[]): Argv; - default(key: string, value: any): Argv; - default(defaults: { [key: string]: any }): Argv; + default(key: string, value: any, description?: string): Argv; + default(defaults: { [key: string]: any }, description?: string): Argv; demand(key: string, msg: string): Argv; demand(key: string, required?: boolean): Argv; @@ -79,6 +73,7 @@ declare namespace yargs { commandDir(dir: string, opts?: RequireDirectoryOptions): Argv; + completion(): Argv; completion(cmd: string, fn?: AsyncCompletionFunction): Argv; completion(cmd: string, fn?: SyncCompletionFunction): Argv; completion(cmd: string, description?: string, fn?: AsyncCompletionFunction): Argv; @@ -94,18 +89,27 @@ declare namespace yargs { string(key: string): Argv; string(keys: string[]): Argv; + number(key: string): Argv; + number(keys: string[]): Argv; + choices(choices: Object): Argv; choices(key: string, values: any[]): Argv; - config(key: string): Argv; - config(keys: string[]): Argv; + config(): Argv; + config(explicitConfigurationObject: Object): Argv; + config(key: string, description?: string, parseFn?: (configPath: string) => Object): Argv; + config(keys: string[], description?: string, parseFn?: (configPath: string) => Object): Argv; + config(key: string, parseFn: (configPath: string) => Object): Argv; + config(keys: string[], parseFn: (configPath: string) => Object): Argv; wrap(columns: number): Argv; strict(): Argv; help(): Argv; - help(option: string, description?: string): Argv; + help(enableExplicit: boolean): Argv; + help(option: string, enableExplicit: boolean): Argv; + help(option: string, description?: string, enableExplicit?: boolean): Argv; env(prefix?: string): Argv; env(enable: boolean): Argv; @@ -118,7 +122,7 @@ declare namespace yargs { showHelpOnFail(enable: boolean, message?: string): Argv; - showHelp(func?: (message: string) => any): Argv; + showHelp(consoleLevel?: string): Argv; exitProcess(enabled: boolean): Argv; @@ -140,10 +144,26 @@ declare namespace yargs { count(key: string): Argv; count(keys: string[]): Argv; - fail(func: (msg: string, err: Error) => any): Argv; + fail(func: (msg: string, err: Error) => any): Argv; coerce(key: string|string[], func: (arg: T) => U): Argv; coerce(opts: { [key: string]: (arg: T) => U; }): Argv; + + getCompletion(args: string[], done: (completions: string[]) => void): Argv; + + pkgConf(key: string, cwd?: string): Argv; + pkgConf(keys: string[], cwd?: string): Argv; + + recommendCommands(): Argv; + + showCompletionScript(): Argv; + + skipValidation(key: string): Argv; + skipValidation(keys: string[]): Argv; + + updateLocale(obj: Object): Argv; + + updateStrings(obj: {[key: string]: string}): Argv; } interface RequireDirectoryOptions { diff --git a/yargs/yargs-tests.ts b/yargs/yargs-tests.ts index 02bcf0695d..011d305621 100644 --- a/yargs/yargs-tests.ts +++ b/yargs/yargs-tests.ts @@ -411,3 +411,92 @@ function Argv$count() { .count(['w', 'h']) .argv } + +function Argv$number() { + var ya = yargs + .number('n') + .number(['width', 'height']) + .argv +} + +function Argv$updateStrings() { + var ya = yargs + .command('run', 'the run command') + .help('help') + .updateStrings({ + 'Commands:': 'My Commands -->\n' + }) + .wrap(null) + .argv +} + +function Argv$default() { + var ya = yargs + .default('random', function randomValue() { + return Math.random() * 256; + }) + .argv +} + +function Argv$configObject() { + var ya = yargs + .config({foo: 1, bar: 2}) + .argv +} + +function Argv$configParseFunction() { + var ya = yargs + .config('settings', function (configPath) { + return JSON.parse(fs.readFileSync(configPath, 'utf-8')) + }) + .config('settings', 'description', function (configPath) { + return JSON.parse(fs.readFileSync(configPath, 'utf-8')) + }) + .argv +} + +function Argv$helpDescriptionExplicit() { + var ya = yargs + .help('help', 'description', true) + .argv +} + +function Argv$showHelpConsoleLevel() { + yargs.showHelp("log"); //prints to stdout using console.log() +} + +function Argv$getCompletion() { + var ya = yargs + .option('foobar', {}) + .option('foobaz', {}) + .completion() + .getCompletion(['./test.js', '--foo'], function (completions) { + console.log(completions) + }) + .argv +} + +function Argv$pkgConf() { + var ya = yargs + .pkgConf(['key1', 'key2'], 'configFile.json') + .argv +} + +function Argv$recommendCommands() { + var ya = yargs + .recommendCommands() + .argv +} + +function Argv$showCompletionScript() { + var ya = yargs + .showCompletionScript() + .argv +} + +function Argv$skipValidation() { + var ya = yargs + .skipValidation('arg1') + .skipValidation(['arg2', 'arg3']) + .argv +} From d6b2438fb4961d053073aa15a5a94bf4c9ffa5b2 Mon Sep 17 00:00:00 2001 From: Giff Song Date: Wed, 2 Nov 2016 22:45:11 +0900 Subject: [PATCH 025/131] [gl-matrix] Add types for submodules (#12209) --- gl-matrix/gl-matrix-tests.ts | 351 +- gl-matrix/index.d.ts | 6000 +++++++++++++++++----------------- 2 files changed, 3370 insertions(+), 2981 deletions(-) diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index a7ea76f353..5df2220f72 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,5 +1,3 @@ - - // common import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "gl-matrix"; @@ -345,3 +343,352 @@ outQuat = quat.fromMat3(outQuat, mat3A); outQuat = quat.calculateW(outQuat, quatA); outBool = quat.exactEquals(quatA, quatB); outBool = quat.equals(quatA, quatB); + +// common +import _vec2 = require('gl-matrix/src/gl-matrix/vec2'); +import _vec3 = require('gl-matrix/src/gl-matrix/vec3'); +import _vec4 = require('gl-matrix/src/gl-matrix/vec4'); +import _mat2 = require('gl-matrix/src/gl-matrix/mat2'); +import _mat2d = require('gl-matrix/src/gl-matrix/mat2d'); +import _mat3 = require('gl-matrix/src/gl-matrix/mat3'); +import _mat4 = require('gl-matrix/src/gl-matrix/mat4'); +import _quat = require('gl-matrix/src/gl-matrix/quat'); + +vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +vec2A = _vec2.fromValues(1, 2); +vec2B = _vec2.fromValues(3, 4); +vec3A = _vec3.fromValues(1, 2, 3); +vec3B = _vec3.fromValues(3, 4, 5); +vec4A = _vec4.fromValues(1, 2, 3, 4); +vec4B = _vec4.fromValues(3, 4, 5, 6); +mat2A = _mat2.fromValues(1, 2, 3, 4); +mat2B = _mat2.fromValues(1, 2, 3, 4); +mat2dA = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +mat2dB = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +mat3A = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +mat3B = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +mat4A = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +mat4B = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +quatA = _quat.fromValues(1, 2, 3, 4); +quatB = _quat.fromValues(5, 6, 7, 8); + +outVec2 = _vec2.create(); +outVec3 = _vec3.create(); +outVec4 = _vec4.create(); +outMat2 = _mat2.create(); +outMat2d = _mat2d.create(); +outMat3 = _mat3.create(); +outMat4 = _mat4.create(); +outQuat = _quat.create(); + +// _vec2 +outVec2 = _vec2.create(); +outVec2 = _vec2.clone(vec2A); +outVec2 = _vec2.fromValues(1, 2); +outVec2 = _vec2.copy(outVec2, vec2A); +outVec2 = _vec2.set(outVec2, 1, 2); +outVec2 = _vec2.add(outVec2, vec2A, vec2B); +outVec2 = _vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = _vec2.sub(outVec2, vec2A, vec2B); +outVec2 = _vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = _vec2.mul(outVec2, vec2A, vec2B); +outVec2 = _vec2.divide(outVec2, vec2A, vec2B); +outVec2 = _vec2.div(outVec2, vec2A, vec2B); +outVec2 = _vec2.ceil(outVec2, vec2A); +outVec2 = _vec2.floor(outVec2, vec2A); +outVec2 = _vec2.min(outVec2, vec2A, vec2B); +outVec2 = _vec2.max(outVec2, vec2A, vec2B); +outVec2 = _vec2.round(outVec2, vec2A); +outVec2 = _vec2.scale(outVec2, vec2A, 2); +outVec2 = _vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = _vec2.distance(vec2A, vec2B); +outVal = _vec2.dist(vec2A, vec2B); +outVal = _vec2.squaredDistance(vec2A, vec2B); +outVal = _vec2.sqrDist(vec2A, vec2B); +outVal = _vec2.length(vec2A); +outVal = _vec2.len(vec2A); +outVal = _vec2.squaredLength(vec2A); +outVal = _vec2.sqrLen(vec2A); +outVec2 = _vec2.negate(outVec2, vec2A); +outVec2 = _vec2.inverse(outVec2, vec2A); +outVec2 = _vec2.normalize(outVec2, vec2A); +outVal = _vec2.dot(vec2A, vec2B); +outVec2 = _vec2.cross(outVec2, vec2A, vec2B); +outVec2 = _vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = _vec2.random(outVec2); +outVec2 = _vec2.random(outVec2, 5.0); +outVec2 = _vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = _vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = _vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = _vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = _vec2.forEach(vecArray, 0, 0, 0, _vec2.normalize); +outStr = _vec2.str(vec2A); +outBool = _vec2.exactEquals(vec2A, vec2B); +outBool = _vec2.equals(vec2A, vec2B); +outVec2 = _vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input + +// _vec3 +outVec3 = _vec3.create(); +outVec3 = _vec3.clone(vec3A); +outVec3 = _vec3.fromValues(1, 2, 3); +outVec3 = _vec3.copy(outVec3, vec3A); +outVec3 = _vec3.set(outVec3, 1, 2, 3); +outVec3 = _vec3.add(outVec3, vec3A, vec3B); +outVec3 = _vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = _vec3.sub(outVec3, vec3A, vec3B); +outVec3 = _vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = _vec3.mul(outVec3, vec3A, vec3B); +outVec3 = _vec3.divide(outVec3, vec3A, vec3B); +outVec3 = _vec3.div(outVec3, vec3A, vec3B); +outVec3 = _vec3.ceil(outVec3, vec3A); +outVec3 = _vec3.floor(outVec3, vec3A); +outVec3 = _vec3.min(outVec3, vec3A, vec3B); +outVec3 = _vec3.max(outVec3, vec3A, vec3B); +outVec3 = _vec3.round(outVec3, vec3A); +outVec3 = _vec3.scale(outVec3, vec3A, 2); +outVec3 = _vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = _vec3.distance(vec3A, vec3B); +outVal = _vec3.dist(vec3A, vec3B); +outVal = _vec3.squaredDistance(vec3A, vec3B); +outVal = _vec3.sqrDist(vec3A, vec3B); +outVal = _vec3.length(vec3A); +outVal = _vec3.len(vec3A); +outVal = _vec3.squaredLength(vec3A); +outVal = _vec3.sqrLen(vec3A); +outVec3 = _vec3.negate(outVec3, vec3A); +outVec3 = _vec3.inverse(outVec3, vec3A); +outVec3 = _vec3.normalize(outVec3, vec3A); +outVal = _vec3.dot(vec3A, vec3B); +outVec3 = _vec3.cross(outVec3, vec3A, vec3B); +outVec3 = _vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = _vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = _vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = _vec3.random(outVec3); +outVec3 = _vec3.random(outVec3, 5.0); +outVec3 = _vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = _vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = _vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = _vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = _vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = _vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = _vec3.forEach(vecArray, 0, 0, 0, _vec3.normalize); +outVal = _vec3.angle(vec3A, vec3B); +outStr = _vec3.str(vec3A); +outBool = _vec3.exactEquals(vec3A, vec3B); +outBool = _vec3.equals(vec3A, vec3B); +outVec3 = _vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input + +// _vec4 +outVec4 = _vec4.create(); +outVec4 = _vec4.clone(vec4A); +outVec4 = _vec4.fromValues(1, 2, 3, 4); +outVec4 = _vec4.copy(outVec4, vec4A); +outVec4 = _vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = _vec4.add(outVec4, vec4A, vec4B); +outVec4 = _vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = _vec4.sub(outVec4, vec4A, vec4B); +outVec4 = _vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = _vec4.mul(outVec4, vec4A, vec4B); +outVec4 = _vec4.divide(outVec4, vec4A, vec4B); +outVec4 = _vec4.div(outVec4, vec4A, vec4B); +outVec4 = _vec4.ceil(outVec4, vec4A); +outVec4 = _vec4.floor(outVec4, vec4A); +outVec4 = _vec4.min(outVec4, vec4A, vec4B); +outVec4 = _vec4.max(outVec4, vec4A, vec4B); +outVec4 = _vec4.scale(outVec4, vec4A, 2); +outVec4 = _vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = _vec4.distance(vec4A, vec4B); +outVal = _vec4.dist(vec4A, vec4B); +outVal = _vec4.squaredDistance(vec4A, vec4B); +outVal = _vec4.sqrDist(vec4A, vec4B); +outVal = _vec4.length(vec4A); +outVal = _vec4.len(vec4A); +outVal = _vec4.squaredLength(vec4A); +outVal = _vec4.sqrLen(vec4A); +outVec4 = _vec4.negate(outVec4, vec4A); +outVec4 = _vec4.inverse(outVec4, vec4A); +outVec4 = _vec4.normalize(outVec4, vec4A); +outVal = _vec4.dot(vec4A, vec4B); +outVec4 = _vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = _vec4.random(outVec4); +outVec4 = _vec4.random(outVec4, 5.0); +outVec4 = _vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = _vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = _vec4.forEach(vecArray, 0, 0, 0, _vec4.normalize); +outStr = _vec4.str(vec4A); +outBool = _vec4.exactEquals(vec4A, vec4B); +outBool = _vec4.equals(vec4A, vec4B); +outVec4 = _vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input + +// _mat2 +outMat2 = _mat2.create(); +outMat2 = _mat2.clone(mat2A); +outMat2 = _mat2.copy(outMat2, mat2A); +outMat2 = _mat2.identity(outMat2); +outMat2 = _mat2.fromValues(1, 2, 3, 4); +outMat2 = _mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = _mat2.transpose(outMat2, mat2A); +outMat2 = _mat2.invert(outMat2, mat2A); +outMat2 = _mat2.adjoint(outMat2, mat2A); +outVal = _mat2.determinant(mat2A); +outMat2 = _mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = _mat2.mul(outMat2, mat2A, mat2B); +outMat2 = _mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = _mat2.scale(outMat2, mat2A, vec2A); +outMat2 = _mat2.fromRotation(outMat2, 0.5); +outMat2 = _mat2.fromScaling(outMat2, vec2A); +outStr = _mat2.str(mat2A); +outVal = _mat2.frob(mat2A); +var L = _mat2.create(); +var D = _mat2.create(); +var U = _mat2.create(); +outMat2 = _mat2.LDU(L, D, U, mat2A); +outMat2 = _mat2.add(outMat2, mat2A, mat2B); +outMat2 = _mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = _mat2.sub(outMat2, mat2A, mat2B); +outBool = _mat2.exactEquals(mat2A, mat2B); +outBool = _mat2.equals(mat2A, mat2B); +outMat2 = _mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = _mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); + +// _mat2d +outMat2d = _mat2d.create(); +outMat2d = _mat2d.clone(mat2dA); +outMat2d = _mat2d.copy(outMat2d, mat2dA); +outMat2d = _mat2d.identity(outMat2d); +outMat2d = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = _mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = _mat2d.invert(outMat2d, mat2dA); +outVal = _mat2d.determinant(mat2dA); +outMat2d = _mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = _mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = _mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = _mat2d.fromRotation(outMat2d, 0.5); +outMat2d = _mat2d.fromScaling(outMat2d, vec2A); +outMat2d = _mat2d.fromTranslation(outMat2d, vec2A); +outStr = _mat2d.str(mat2dA); +outVal = _mat2d.frob(mat2dA); +outMat2d = _mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = _mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = _mat2d.exactEquals(mat2dA, mat2dB); +outBool = _mat2d.equals(mat2dA, mat2dB); + +// _mat3 +outMat3 = _mat3.create(); +outMat3 = _mat3.fromMat4(outMat3, mat4A); +outMat3 = _mat3.clone(mat3A); +outMat3 = _mat3.copy(outMat3, mat3A); +outMat3 = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = _mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = _mat3.identity(outMat3); +outMat3 = _mat3.transpose(outMat3, mat3A); +outMat3 = _mat3.invert(outMat3, mat3A); +outMat3 = _mat3.adjoint(outMat3, mat3A); +outVal = _mat3.determinant(mat3A); +outMat3 = _mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = _mat3.mul(outMat3, mat3A, mat3B); +outMat3 = _mat3.translate(outMat3, mat3A, vec3A); +outMat3 = _mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = _mat3.scale(outMat3, mat3A, vec2A); +outMat3 = _mat3.fromTranslation(outMat3, vec2A); +outMat3 = _mat3.fromRotation(outMat3, Math.PI); +outMat3 = _mat3.fromScaling(outMat3, vec2A); +outMat3 = _mat3.fromMat2d(outMat3, mat2dA); +outMat3 = _mat3.fromQuat(outMat3, quatA); +outMat3 = _mat3.normalFromMat4(outMat3, mat4A); +outStr = _mat3.str(mat3A); +outVal = _mat3.frob(mat3A); +outMat3 = _mat3.add(outMat3, mat3A, mat3B); +outMat3 = _mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = _mat3.sub(outMat3, mat3A, mat3B); +outMat3 = _mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = _mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = _mat3.exactEquals(mat3A, mat3B); +outBool = _mat3.equals(mat3A, mat3B); + +//_mat4 +outMat4 = _mat4.create(); +outMat4 = _mat4.clone(mat4A); +outMat4 = _mat4.copy(outMat4, mat4A); +outMat4 = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = _mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = _mat4.identity(outMat4); +outMat4 = _mat4.transpose(outMat4, mat4A); +outMat4 = _mat4.invert(outMat4, mat4A); +outMat4 = _mat4.adjoint(outMat4, mat4A); +outVal = _mat4.determinant(mat4A); +outMat4 = _mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = _mat4.mul(outMat4, mat4A, mat4B); +outMat4 = _mat4.translate(outMat4, mat4A, vec3A); +outMat4 = _mat4.scale(outMat4, mat4A, vec3A); +outMat4 = _mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = _mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = _mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = _mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = _mat4.fromTranslation(outMat4, vec3A); +outMat4 = _mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = _mat4.fromScaling(outMat4, vec3A); +outMat4 = _mat4.fromXRotation(outMat4, Math.PI); +outMat4 = _mat4.fromYRotation(outMat4, Math.PI); +outMat4 = _mat4.fromZRotation(outMat4, Math.PI); +outMat4 = _mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = _mat4.getTranslation(outVec3, mat4A) +outQuat = _mat4.getRotation(outQuat, mat4A) +outMat4 = _mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = _mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = _mat4.fromQuat(outMat4, quatB); +outMat4 = _mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = _mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = _mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = _mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = _mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = _mat4.str(mat4A); +outVal = _mat4.frob(mat4A); +outMat4 = _mat4.add(outMat4, mat4A, mat4B); +outMat4 = _mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = _mat4.sub(outMat4, mat4A, mat4B); +outMat4 = _mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = _mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = _mat4.exactEquals(mat4A, mat4B); +outBool = _mat4.equals(mat4A, mat4B); + +// _quat +var deg90 = Math.PI / 2; +outQuat = _quat.create(); +outQuat = _quat.clone(quatA); +outQuat = _quat.fromValues(1, 2, 3, 4); +outQuat = _quat.copy(outQuat, quatA); +outQuat = _quat.set(outQuat, 1, 2, 3, 4); +outQuat = _quat.identity(outQuat); +outQuat = _quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = _quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = _quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = _quat.getAxisAngle (outVec3, quatA); +outQuat = _quat.add(outQuat, quatA, quatB); +outQuat = _quat.multiply(outQuat, quatA, quatB); +outQuat = _quat.mul(outQuat, quatA, quatB); +outQuat = _quat.scale(outQuat, quatA, 2); +outVal = _quat.length(quatA); +outVal = _quat.len(quatA); +outVal = _quat.squaredLength(quatA); +outVal = _quat.sqrLen(quatA); +outQuat = _quat.normalize(outQuat, quatA); +outVal = _quat.dot(quatA, quatB); +outQuat = _quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = _quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = _quat.invert(outQuat, quatA); +outQuat = _quat.conjugate(outQuat, quatA); +outStr = _quat.str(quatA); +outQuat = _quat.rotateX(outQuat, quatA, deg90); +outQuat = _quat.rotateY(outQuat, quatA, deg90); +outQuat = _quat.rotateZ(outQuat, quatA, deg90); +outQuat = _quat.fromMat3(outQuat, mat3A); +outQuat = _quat.calculateW(outQuat, quatA); +outBool = _quat.exactEquals(quatA, quatB); +outBool = _quat.equals(quatA, quatB); diff --git a/gl-matrix/index.d.ts b/gl-matrix/index.d.ts index 2edbbd8bb5..b8a6694e40 100644 --- a/gl-matrix/index.d.ts +++ b/gl-matrix/index.d.ts @@ -3,3042 +3,3084 @@ // Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// vec2 -export class vec2 extends Float32Array { - private typeVec2: number; +declare module 'gl-matrix' { + // vec2 + export class vec2 extends Float32Array { + private typeVec2: number; - /** - * Creates a new, empty vec2 - * - * @returns a new 2D vector - */ - public static create(): vec2; + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + public static create(): vec2; - /** - * Creates a new vec2 initialized with values from an existing vector - * - * @param a a vector to clone - * @returns a new 2D vector - */ - public static clone(a: vec2 | number[]): vec2; + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + public static clone(a: vec2 | number[]): vec2; - /** - * Creates a new vec2 initialized with the given values - * - * @param x X component - * @param y Y component - * @returns a new 2D vector - */ - public static fromValues(x: number, y: number): vec2; + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + public static fromValues(x: number, y: number): vec2; - /** - * Copy the values from one vec2 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec2, a: vec2 | number[]): vec2; + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec2, a: vec2 | number[]): vec2; - /** - * Set the components of a vec2 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @returns out - */ - public static set(out: vec2, x: number, y: number): vec2; + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + public static set(out: vec2, x: number, y: number): vec2; - /** - * Adds two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Math.ceil the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to ceil - * @returns {vec2} out - */ - public static ceil(out: vec2, a: vec2 | number[]): vec2; + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out: vec2, a: vec2 | number[]): vec2; - /** - * Math.floor the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to floor - * @returns {vec2} out - */ - public static floor (out: vec2, a: vec2 | number[]): vec2; + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out: vec2, a: vec2 | number[]): vec2; - /** - * Returns the minimum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Returns the maximum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Math.round the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to round - * @returns {vec2} out - */ - public static round(out: vec2, a: vec2 | number[]): vec2; + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out: vec2, a: vec2 | number[]): vec2; - /** - * Scales a vec2 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec2, a: vec2 | number[], b: number): vec2; + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; - /** - * Adds two vec2's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec2 | number[]): number; + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec2 | number[]): number; - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec2 | number[]): number; + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec2 | number[]): number; - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec2 | number[]): number; + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec2 | number[]): number; - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec2 | number[]): number; + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec2 | number[]): number; - /** - * Negates the components of a vec2 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec2, a: vec2 | number[]): vec2; + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec2, a: vec2 | number[]): vec2; - /** - * Returns the inverse of the components of a vec2 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec2, a: vec2 | number[]): vec2; + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec2, a: vec2 | number[]): vec2; - /** - * Normalize a vec2 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec2, a: vec2 | number[]): vec2; + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec2, a: vec2 | number[]): vec2; - /** - * Calculates the dot product of two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Computes the cross product of two vec2's - * Note that the cross product must by definition produce a 3D vector - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Performs a linear interpolation between two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec2): vec2; + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec2): vec2; - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec2, scale: number): vec2; + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec2, scale: number): vec2; - /** - * Transforms the vec2 with a mat2 - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; - /** - * Transforms the vec2 with a mat2d - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; - /** - * Transforms the vec2 with a mat3 - * 3rd vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; - /** - * Transforms the vec2 with a mat4 - * 3rd vector component is implicitly '0' - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec2 | number[]): string; + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec2 | number[]): string; - /** - * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; + } + + // vec3 + export class vec3 extends Float32Array { + private typeVec3: number; + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + public static create(): vec3; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + public static clone(a: vec3 | number[]): vec3; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + public static fromValues(x: number, y: number, z: number): vec3; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec3, a: vec3 | number[]): vec3; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + public static set(out: vec3, x: number, y: number, z: number): vec3; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out: vec3, a: vec3 | number[]): vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out: vec3, a: vec3 | number[]): vec3; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out: vec3, a: vec3 | number[]): vec3 + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec3 | number[]): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec3, a: vec3 | number[]): vec3; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec3, a: vec3 | number[]): vec3; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec3, a: vec3 | number[]): vec3; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec3): vec3; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec3, scale: number): vec3; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; + + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean + } + + // vec4 + export class vec4 extends Float32Array { + private typeVec3: number; + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + public static create(): vec4; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + public static clone(a: vec4 | number[]): vec4; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + public static fromValues(x: number, y: number, z: number, w: number): vec4; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec4, a: vec4 | number[]): vec4; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out: vec4, a: vec4 | number[]): vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out: vec4, a: vec4 | number[]): vec4; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out: vec4, a: vec4 | number[]): vec4; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec4 | number[]): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec4, a: vec4 | number[]): vec4; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec4, a: vec4 | number[]): vec4; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec4, a: vec4 | number[]): vec4; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec4): vec4; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec4, scale: number): vec4; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; + } + + // mat2 + export class mat2 extends Float32Array { + private typeMat2: number; + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + public static create(): mat2; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + public static clone(a: mat2): mat2; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2, a: mat2): mat2; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2): mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat2, a: mat2): mat2; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2, a: mat2): mat2; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat2, a: mat2): mat2; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2, a: mat2, rad: number): mat2; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out: mat2, rad: number): mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2, b: mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2, b: mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 + + + + } + + // mat2d + export class mat2d extends Float32Array { + private typeMat2d: number; + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + public static create(): mat2d; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + public static clone(a: mat2d): mat2d; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2d, a: mat2d): mat2d; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2d, a: mat2d): mat2d; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2d): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out: mat2d, rad: number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2d): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean + } + + // mat3 + export class mat3 extends Float32Array { + private typeMat3: number; + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + public static create(): mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out: mat3, a: mat4): mat3 + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + public static clone(a: mat3): mat3; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat3, a: mat3): mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat3): mat3; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat3, a: mat3): mat3; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat3, a: mat3): mat3; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat3, a: mat3): mat3; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat3): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat3, a: mat3, b: mat3): mat3; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat3, a: mat3, b: mat3): mat3; + + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat3, a: mat3, rad: number): mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out: mat3, rad: number): mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out: mat3, a: mat2d): mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out: mat3, q: quat): mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out: mat3, a: mat4): mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a: mat3, b: mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a: mat3, b: mat3): boolean + } + + // mat4 + export class mat4 extends Float32Array { + private typeMat4: number; + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + public static create(): mat4; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + public static clone(a: mat4): mat4; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat4, a: mat4): mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat4): mat4; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat4, a: mat4): mat4; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat4, a: mat4): mat4; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat4, a: mat4): mat4; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat4): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat4, a: mat4, b: mat4): mat4; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat4, a: mat4, b: mat4): mat4; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateX(out: mat4, a: mat4, rad: number): mat4; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateY(out: mat4, a: mat4, rad: number): mat4; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 + + /** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 + + /** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromXRotation(out: mat4, rad: number): mat4 + + /** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromYRotation(out: mat4, rad: number): mat4 + + + /** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromZRotation(out: mat4, rad: number): mat4 + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; + + /** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out: vec3, mat: mat4): vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out: quat, mat: mat4): quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @returns out + */ + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out: mat4, q: quat): mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out: mat4, + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat4, b: mat4): boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat4, b: mat4): boolean + + } + + // quat + export class quat extends Float32Array { + private typeQuat: number; + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + public static create(): quat; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + public static clone(a: quat): quat; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + public static fromValues(x: number, y: number, z: number, w: number): quat; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + public static copy(out: quat, a: quat): quat; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + public static set(out: quat, x: number, y: number, z: number, w: number): quat; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + public static add(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: quat, a: quat, b: quat): quat; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + public static scale(out: quat, a: quat, b: number): quat; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static length(a: quat): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static len(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static squaredLength(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static sqrLen(a: quat): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + public static normalize(out: quat, a: quat): quat; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + public static dot(a: quat, b: quat): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + public static lerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static slerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + public static invert(out: quat, a: quat): quat; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + public static conjugate(out: quat, a: quat): quat; + + /** + * Returns a string representation of a quaternion + * + * @param a quat to represent as a string + * @returns string representation of the quat + */ + public static str(a: quat): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateX(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateY(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateZ(out: quat, a: quat, rad: number): quat; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + public static fromMat3(out: quat, m: mat3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param out the receiving quat + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a: quat, b: quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a: quat, b: quat): boolean; + } } -// vec3 -export class vec3 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec3 - * - * @returns a new 3D vector - */ - public static create(): vec3; - - /** - * Creates a new vec3 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 3D vector - */ - public static clone(a: vec3 | number[]): vec3; - - /** - * Creates a new vec3 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @returns a new 3D vector - */ - public static fromValues(x: number, y: number, z: number): vec3; - - /** - * Copy the values from one vec3 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec3, a: vec3 | number[]): vec3; - - /** - * Set the components of a vec3 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @returns out - */ - public static set(out: vec3, x: number, y: number, z: number): vec3; - - /** - * Adds two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.ceil the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to ceil - * @returns {vec3} out - */ - public static ceil (out: vec3, a: vec3 | number[]): vec3; - - /** - * Math.floor the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to floor - * @returns {vec3} out - */ - public static floor (out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the minimum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Returns the maximum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.round the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to round - * @returns {vec3} out - */ - public static round (out: vec3, a: vec3 | number[]): vec3 - - /** - * Scales a vec3 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec3, a: vec3 | number[], b: number): vec3; - - /** - * Adds two vec3's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec3 | number[]): number; - - /** - * Negates the components of a vec3 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the inverse of the components of a vec3 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec3, a: vec3 | number[]): vec3; - - /** - * Normalize a vec3 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec3, a: vec3 | number[]): vec3; - - /** - * Calculates the dot product of two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Computes the cross product of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Performs a linear interpolation between two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; - - /** - * Performs a hermite interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Performs a bezier interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec3): vec3; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec3, scale: number): vec3; - - /** - * Transforms the vec3 with a mat3. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m the 3x3 matrix to transform with - * @returns out - */ - public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; - - /** - * Transforms the vec3 with a mat4. - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - - /** - * Transforms the vec3 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; - - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; - - /** - * Get the angle between two 3D vectors - * @param a The first operand - * @param b The second operand - * @returns The angle in radians - */ - public static angle(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec3 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec3 | number[], b: vec3 | number[]): boolean +declare module 'gl-matrix/src/gl-matrix/vec2' { + import { vec2 } from 'gl-matrix'; + export = vec2; } -// vec4 -export class vec4 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec4 - * - * @returns a new 4D vector - */ - public static create(): vec4; - - /** - * Creates a new vec4 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 4D vector - */ - public static clone(a: vec4 | number[]): vec4; - - /** - * Creates a new vec4 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new 4D vector - */ - public static fromValues(x: number, y: number, z: number, w: number): vec4; - - /** - * Copy the values from one vec4 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec4, a: vec4 | number[]): vec4; - - /** - * Set the components of a vec4 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - */ - public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; - - /** - * Adds two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.ceil the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to ceil - * @returns {vec4} out - */ - public static ceil (out: vec4, a: vec4 | number[]): vec4; - - /** - * Math.floor the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to floor - * @returns {vec4} out - */ - public static floor (out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the minimum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Returns the maximum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.round the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to round - * @returns {vec4} out - */ - public static round (out: vec4, a: vec4 | number[]): vec4; - - /** - * Scales a vec4 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec4, a: vec4 | number[], b: number): vec4; - - /** - * Adds two vec4's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec4 | number[]): number; - - /** - * Negates the components of a vec4 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the inverse of the components of a vec4 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec4, a: vec4 | number[]): vec4; - - /** - * Normalize a vec4 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec4, a: vec4 | number[]): vec4; - - /** - * Calculates the dot product of two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Performs a linear interpolation between two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec4): vec4; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec4, scale: number): vec4; - - /** - * Transforms the vec4 with a mat4. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; - - /** - * Transforms the vec4 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - - public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec4 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; +declare module 'gl-matrix/src/gl-matrix/vec3' { + import { vec3 } from 'gl-matrix'; + export = vec3; } -// mat2 -export class mat2 extends Float32Array { - private typeMat2: number; - - /** - * Creates a new identity mat2 - * - * @returns a new 2x2 matrix - */ - public static create(): mat2; - - /** - * Creates a new mat2 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x2 matrix - */ - public static clone(a: mat2): mat2; - - /** - * Copy the values from one mat2 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2, a: mat2): mat2; - - /** - * Set a mat2 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2): mat2; - - /** - * Create a new mat2 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out A new 2x2 matrix - */ - public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Set the components of a mat2 to the given values - * - * @param {mat2} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out - */ - public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Transpose the values of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat2, a: mat2): mat2; - - /** - * Inverts a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2, a: mat2): mat2; - - /** - * Calculates the adjugate of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat2, a: mat2): mat2; - - /** - * Calculates the determinant of a mat2 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2): number; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Rotates a mat2 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2, a: mat2, rad: number): mat2; - - /** - * Scales the mat2 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.rotate(dest, dest, rad); - * - * @param {mat2} out mat2 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - public static fromRotation(out: mat2, rad: number): mat2; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.scale(dest, dest, vec); - * - * @param {mat2} out mat2 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2} out - */ - public static fromScaling(out: mat2, v: vec2 | number[]): mat2; - - /** - * Returns a string representation of a mat2 - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2): string; - - /** - * Returns Frobenius norm of a mat2 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2): number; - - /** - * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix - * @param L the lower triangular matrix - * @param D the diagonal matrix - * @param U the upper triangular matrix - * @param a the input matrix to factorize - */ - public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; - - /** - * Adds two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static add(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static subtract (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static sub (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2, b: mat2): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2, b: mat2): boolean; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2} out - */ - public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 - - /** - * Adds two mat2's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2} out the receiving vector - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2} out - */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 - - - +declare module 'gl-matrix/src/gl-matrix/vec4' { + import { vec4 } from 'gl-matrix'; + export = vec4; } -// mat2d -export class mat2d extends Float32Array { - private typeMat2d: number; - - /** - * Creates a new identity mat2d - * - * @returns a new 2x3 matrix - */ - public static create(): mat2d; - - /** - * Creates a new mat2d initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x3 matrix - */ - public static clone(a: mat2d): mat2d; - - /** - * Copy the values from one mat2d to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2d, a: mat2d): mat2d; - - /** - * Set a mat2d to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2d): mat2d; - - /** - * Create a new mat2d with the given values - * - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} A new mat2d - */ - public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - - /** - * Set the components of a mat2d to the given values - * - * @param {mat2d} out the receiving matrix - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} out - */ - public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - /** - * Inverts a mat2d - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2d, a: mat2d): mat2d; - - /** - * Calculates the determinant of a mat2d - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2d): number; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Rotates a mat2d by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; - - /** - * Scales the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Translates the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to translate the matrix by - * @returns out - **/ - public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.rotate(dest, dest, rad); - * - * @param {mat2d} out mat2d receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2d} out - */ - public static fromRotation (out: mat2d, rad: number): mat2d; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.scale(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2d} out - */ - public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.translate(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Translation vector - * @returns {mat2d} out - */ - public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d - - /** - * Returns a string representation of a mat2d - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2d): string; - - /** - * Returns Frobenius norm of a mat2d - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2d): number; - - /** - * Adds two mat2d's - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static add (out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2d} out - */ - public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; - - /** - * Adds two mat2d's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2d} out the receiving vector - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2d} out - */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2d, b: mat2d): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2d, b: mat2d): boolean +declare module 'gl-matrix/src/gl-matrix/mat2' { + import { mat2 } from 'gl-matrix'; + export = mat2; } -// mat3 -export class mat3 extends Float32Array { - private typeMat3: number; - - /** - * Creates a new identity mat3 - * - * @returns a new 3x3 matrix - */ - public static create(): mat3; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param {mat3} out the receiving 3x3 matrix - * @param {mat4} a the source 4x4 matrix - * @returns {mat3} out - */ - public static fromMat4(out: mat3, a: mat4): mat3 - - /** - * Creates a new mat3 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 3x3 matrix - */ - public static clone(a: mat3): mat3; - - /** - * Copy the values from one mat3 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat3, a: mat3): mat3; - - /** - * Create a new mat3 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} A new mat3 - */ - public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; - - - /** - * Set the components of a mat3 to the given values - * - * @param {mat3} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} out - */ - public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 - - /** - * Set a mat3 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat3): mat3; - - /** - * Transpose the values of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat3, a: mat3): mat3; - - /** - * Inverts a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat3, a: mat3): mat3; - - /** - * Calculates the adjugate of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat3, a: mat3): mat3; - - /** - * Calculates the determinant of a mat3 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat3): number; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat3, a: mat3, b: mat3): mat3; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat3, a: mat3, b: mat3): mat3; - - - /** - * Translate a mat3 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; - - /** - * Rotates a mat3 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat3, a: mat3, rad: number): mat3; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.translate(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat3} out - */ - public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.rotate(dest, dest, rad); - * - * @param {mat3} out mat3 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - public static fromRotation(out: mat3, rad: number): mat3 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.scale(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat3} out - */ - public static fromScaling(out: mat3, v: vec2 | number[]): mat3 - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - public static fromMat2d(out: mat3, a: mat2d): mat3; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - public static fromQuat(out: mat3, q: quat): mat3; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - public static normalFromMat4(out: mat3, a: mat4): mat3; - - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat3): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat3): number; - - /** - * Adds two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static add(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static subtract(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static sub(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat3} out - */ - public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 - - /** - * Adds two mat3's after multiplying each element of the second operand by a scalar value. - * - * @param {mat3} out the receiving vector - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat3} out - */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals(a: mat3, b: mat3): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals(a: mat3, b: mat3): boolean +declare module 'gl-matrix/src/gl-matrix/mat2d' { + import { mat2d } from 'gl-matrix'; + export = mat2d; } -// mat4 -export class mat4 extends Float32Array { - private typeMat4: number; - - /** - * Creates a new identity mat4 - * - * @returns a new 4x4 matrix - */ - public static create(): mat4; - - /** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 4x4 matrix - */ - public static clone(a: mat4): mat4; - - /** - * Copy the values from one mat4 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat4, a: mat4): mat4; - - - /** - * Create a new mat4 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} A new mat4 - */ - public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set the components of a mat4 to the given values - * - * @param {mat4} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} out - */ - public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set a mat4 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat4): mat4; - - /** - * Transpose the values of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat4, a: mat4): mat4; - - /** - * Inverts a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat4, a: mat4): mat4; - - /** - * Calculates the adjugate of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat4, a: mat4): mat4; - - /** - * Calculates the determinant of a mat4 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat4): number; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Translate a mat4 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param out the receiving matrix - * @param a the matrix to scale - * @param v the vec3 to scale the matrix by - * @returns out - **/ - public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Rotates a mat4 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @param axis the axis to rotate around - * @returns out - */ - public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; - - /** - * Rotates a matrix by the given angle around the X axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateX(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Y axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateY(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Z axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateZ(out: mat4, a: mat4, rad: number): mat4; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.scale(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Scaling vector - * @returns {mat4} out - */ - public static fromScaling(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a given angle around a given axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotate(dest, dest, rad, axis); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 - - /** - * Creates a matrix from the given angle around the X axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateX(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromXRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from the given angle around the Y axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateY(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromYRotation(out: mat4, rad: number): mat4 - - - /** - * Creates a matrix from the given angle around the Z axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateZ(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromZRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @returns out - */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; - - /** - * Returns the translation vector component of a transformation - * matrix. If a matrix is built with fromRotationTranslation, - * the returned vector will be the same as the translation vector - * originally supplied. - * @param {vec3} out Vector to receive translation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - public static getTranslation(out: vec3, mat: mat4): vec3; - - /** - * Returns a quaternion representing the rotational component - * of a transformation matrix. If a matrix is built with - * fromRotationTranslation, the returned quaternion will be the - * same as the quaternion originally supplied. - * @param {quat} out Quaternion to receive the rotation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {quat} out - */ - public static getRotation(out: quat, mat: mat4): quat; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scaling vector - * @returns out - */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * mat4.translate(dest, origin); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * mat4.translate(dest, negativeOrigin); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @param {vec3} o The origin vector around which to scale and rotate - * @returns {mat4} out - */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 - - /** - * Calculates a 4x4 matrix from the given quaternion - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat4} out - */ - public static fromQuat(out: mat4, q: quat): mat4 - - /** - * Generates a frustum matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static frustum(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static perspective(out: mat4, fovy: number, aspect: number, - near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given field of view. - * This is primarily useful for generating projection matrices to be used - * with the still experimental WebVR API. - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, - near: number, far: number): mat4 - - /** - * Generates a orthogonal projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static ortho(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out - */ - public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; - - /** - * Returns a string representation of a mat4 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat4): string; - - /** - * Returns Frobenius norm of a mat4 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat4): number; - - /** - * Adds two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static add(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static subtract(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static sub(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat4} out - */ - public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 - - /** - * Adds two mat4's after multiplying each element of the second operand by a scalar value. - * - * @param {mat4} out the receiving vector - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat4} out - */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat4, b: mat4): boolean - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat4, b: mat4): boolean - +declare module 'gl-matrix/src/gl-matrix/mat3' { + import { mat3 } from 'gl-matrix'; + export = mat3; } -// quat -export class quat extends Float32Array { - private typeQuat: number; - - /** - * Creates a new identity quat - * - * @returns a new quaternion - */ - public static create(): quat; - - /** - * Creates a new quat initialized with values from an existing quaternion - * - * @param a quaternion to clone - * @returns a new quaternion - * @function - */ - public static clone(a: quat): quat; - - /** - * Creates a new quat initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new quaternion - * @function - */ - public static fromValues(x: number, y: number, z: number, w: number): quat; - - /** - * Copy the values from one quat to another - * - * @param out the receiving quaternion - * @param a the source quaternion - * @returns out - * @function - */ - public static copy(out: quat, a: quat): quat; - - /** - * Set the components of a quat to the given values - * - * @param out the receiving quaternion - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - * @function - */ - public static set(out: quat, x: number, y: number, z: number, w: number): quat; - - /** - * Set a quat to the identity quaternion - * - * @param out the receiving quaternion - * @returns out - */ - public static identity(out: quat): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out the receiving quaternion. - * @param {vec3} a the initial vector - * @param {vec3} b the destination vector - * @returns {quat} out - */ - public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat - - - - /** - * Sets a quat from the given angle and rotation axis, - * then returns it. - * - * @param out the receiving quaternion - * @param axis the axis around which to rotate - * @param rad the angle in radians - * @returns out - **/ - public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * setAxisAngle, this method will return the same - * values as providied in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis Vector receiving the axis of rotation - * @param {quat} q Quaternion to be decomposed - * @return {number} Angle, in radians, of the rotation - */ - public static getAxisAngle (out_axis: vec3 | number[], q: quat): number - - /** - * Adds two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - * @function - */ - public static add(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: quat, a: quat, b: quat): quat; - - /** - * Scales a quat by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - * @function - */ - public static scale(out: quat, a: quat, b: number): quat; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static length(a: quat): number; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static len(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static squaredLength(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static sqrLen(a: quat): number; - - /** - * Normalize a quat - * - * @param out the receiving quaternion - * @param a quaternion to normalize - * @returns out - * @function - */ - public static normalize(out: quat, a: quat): quat; - - /** - * Calculates the dot product of two quat's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - * @function - */ - public static dot(a: quat, b: quat): number; - - /** - * Performs a linear interpolation between two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - * @function - */ - public static lerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation between two quat - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static slerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation with two control points - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {quat} c the third operand - * @param {quat} d the fourth operand - * @param {number} t interpolation amount - * @returns {quat} out - */ - public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; - - /** - * Calculates the inverse of a quat - * - * @param out the receiving quaternion - * @param a quat to calculate inverse of - * @returns out - */ - public static invert(out: quat, a: quat): quat; - - /** - * Calculates the conjugate of a quat - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param out the receiving quaternion - * @param a quat to calculate conjugate of - * @returns out - */ - public static conjugate(out: quat, a: quat): quat; - - /** - * Returns a string representation of a quaternion - * - * @param a quat to represent as a string - * @returns string representation of the quat - */ - public static str(a: quat): string; - - /** - * Rotates a quaternion by the given angle about the X axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateX(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Y axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateY(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Z axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateZ(out: quat, a: quat, rad: number): quat; - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to renormalize the quaternion yourself where necessary. - * - * @param out the receiving quaternion - * @param m rotation matrix - * @returns out - * @function - */ - public static fromMat3(out: quat, m: mat3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param out the receiving quat - * @param view the vector representing the viewing direction - * @param right the vector representing the local "right" direction - * @param up the vector representing the local "up" direction - * @returns out - */ - public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param out the receiving quaternion. - * @param a the initial vector - * @param b the destination vector - * @returns out - */ - public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Calculates the W component of a quat from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param out the receiving quaternion - * @param a quat to calculate W component of - * @returns out - */ - public static calculateW(out: quat, a: quat): quat; - - /** - * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static exactEquals (a: quat, b: quat): boolean; - - /** - * Returns whether or not the quaternions have approximately the same elements in the same position. - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static equals (a: quat, b: quat): boolean; +declare module 'gl-matrix/src/gl-matrix/mat4' { + import { mat4 } from 'gl-matrix'; + export = mat4; +} + +declare module 'gl-matrix/src/gl-matrix/quat' { + import { quat } from 'gl-matrix'; + export = quat; } From ec7779fb1a9e1ec05050319ed3a034ce1d98d781 Mon Sep 17 00:00:00 2001 From: Melvin Groenhoff Date: Wed, 2 Nov 2016 14:46:47 +0100 Subject: [PATCH 026/131] Change milliseconds argument type from boolean to number. (#12409) --- socket.io-client/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/socket.io-client/index.d.ts b/socket.io-client/index.d.ts index 9bc6e1185c..f4aef879a8 100644 --- a/socket.io-client/index.d.ts +++ b/socket.io-client/index.d.ts @@ -410,7 +410,7 @@ declare namespace SocketIOClient { * @param The connection timeout milliseconds * @return This Manager */ - timeout(v: boolean): Manager; + timeout(v: number): Manager; /** * Sets the current transport socket and opens our connection From 513dc337f95120a93d6abfecc41714ee08090cbf Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Wed, 2 Nov 2016 15:00:10 +0100 Subject: [PATCH 027/131] Rewrite WebRTC RTCPeerConnection definitions (#12140) * Rewrite all RTCPeerConnection definitions I used the specification IDL to rewrite all definitions. * RTCPeerConnection: Add legacy interface extensions --- webrtc/MediaStream.d.ts | 95 ++++ webrtc/RTCPeerConnection-tests.ts | 185 +++---- webrtc/RTCPeerConnection.d.ts | 807 +++++++++++++++++------------- webrtc/readme.md | 18 +- 4 files changed, 637 insertions(+), 468 deletions(-) diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index e10d742427..bb25e57c66 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -6,6 +6,11 @@ // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html // version: W3C Editor's Draft 29 June 2015 +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + interface NumberRange { max?: number; min?: number; @@ -21,6 +26,11 @@ interface ConstrainStringParameters { ideal?: string | string[]; } +interface MediaStreamConstraints { + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; +} + declare namespace W3C { type LongRange = NumberRange; type DoubleRange = NumberRange; @@ -31,16 +41,49 @@ declare namespace W3C { type ConstrainString = string | string[] | ConstrainStringParameters; } +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + interface MediaTrackConstraintSet { + width?: W3C.ConstrainLong; + height?: W3C.ConstrainLong; + aspectRatio?: W3C.ConstrainDouble; + frameRate?: W3C.ConstrainDouble; + facingMode?: W3C.ConstrainString; + volume?: W3C.ConstrainDouble; + sampleRate?: W3C.ConstrainLong; + sampleSize?: W3C.ConstrainLong; echoCancellation?: W3C.ConstrainBoolean; latency?: W3C.ConstrainDouble; + deviceId?: W3C.ConstrainString; + groupId?: W3C.ConstrainString; } interface MediaTrackSupportedConstraints { + width?: boolean; + height?: boolean; + aspectRatio?: boolean; + frameRate?: boolean; + facingMode?: boolean; + volume?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + echoCancellation?: boolean; latency?: boolean; + deviceId?: boolean; + groupId?: boolean; } interface MediaStream extends EventTarget { + //id: string; + //active: boolean; + + //onactive: EventListener; + //oninactive: EventListener; + //onaddtrack: (event: MediaStreamTrackEvent) => any; + //onremovetrack: (event: MediaStreamTrackEvent) => any; + clone(): MediaStream; stop(): void; @@ -54,12 +97,29 @@ interface MediaStream extends EventTarget { removeTrack(track: MediaStreamTrack): void; } +interface MediaStreamTrackEvent extends Event { + //track: MediaStreamTrack; +} + declare enum MediaStreamTrackState { "live", "ended" } interface MediaStreamTrack extends EventTarget { + //id: string; + //kind: string; + //label: string; + enabled: boolean; + //muted: boolean; + //remote: boolean; + //readyState: MediaStreamTrackState; + + //onmute: EventListener; + //onunmute: EventListener; + //onended: EventListener; + //onoverconstrained: EventListener; + clone(): MediaStreamTrack; stop(): void; @@ -71,11 +131,39 @@ interface MediaStreamTrack extends EventTarget { } interface MediaTrackCapabilities { + //width: number | W3C.LongRange; + //height: number | W3C.LongRange; + //aspectRatio: number | W3C.DoubleRange; + //frameRate: number | W3C.DoubleRange; + //facingMode: string; + //volume: number | W3C.DoubleRange; + //sampleRate: number | W3C.LongRange; + //sampleSize: number | W3C.LongRange; + //echoCancellation: boolean[]; latency: number | W3C.DoubleRange; + //deviceId: string; + //groupId: string; } interface MediaTrackSettings { + //width: number; + //height: number; + //aspectRatio: number; + //frameRate: number; + //facingMode: string; + //volume: number; + //sampleRate: number; + //sampleSize: number; + //echoCancellation: boolean; latency: number; + //deviceId: string; + //groupId: string; +} + +interface MediaStreamError { + //name: string; + //message: string; + //constraintName: string; } interface NavigatorGetUserMedia { @@ -105,3 +193,10 @@ interface MediaDevices { getUserMedia(constraints: MediaStreamConstraints): Promise; enumerateDevices(): Promise; } + +interface MediaDeviceInfo { + //label: string; + //deviceId: string; + //kind: string; + //groupId: string; +} diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index 75cc5f2ff6..dcb6bf8657 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -1,114 +1,91 @@ +/// +/// +let defaultIceServers: RTCIceServer[] = RTCPeerConnection.defaultIceServers; +if (defaultIceServers.length > 0) { + let urls = defaultIceServers[0].urls; +} - -let voidpromise: Promise; - -var minimalConfig: RTCConfiguration = {}; -var config: RTCConfiguration = { - iceServers: [ - { - // Single url - urls: "stun.l.google.com:19302" - }, - { - // List of urls and credentials - urls: ["another-stun.example.com"], - username: "dude", - credential: "pass", - credentialType: "token" - }, - ], - iceTransportPolicy: "relay", - bundlePolicy: "max-compat", - rtcpMuxPolicy: "negotiate", - peerIdentity: "dude", - certificates: [{ expires: 1337 }], - iceCandidatePoolSize: 5 +// Create a peer connection +let ice1: RTCIceServer = { + 'urls': 'stun:stun.l.google.com:19302', + 'username': 'john', + 'credential': '1234', + 'credentialType': 'password', }; -var constraints: RTCMediaConstraints = - { mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: true } }; - -var peerConnection: RTCPeerConnection = - new RTCPeerConnection(config, constraints); - -navigator.getUserMedia({ audio: true, video: true }, - stream => { - peerConnection.addStream(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); +let ice2: RTCIceServer = {'urls': ['stun:stunserver.org', 'stun:stun.example.com']}; +let pc: RTCPeerConnection = new RTCPeerConnection(); +let pc2: RTCPeerConnection = new RTCPeerConnection({ + iceServers: [ice1, ice2], +}); +RTCPeerConnection.generateCertificate("sha-256").then((cert: RTCCertificate) => { + new RTCPeerConnection({ + iceServers: [ice1], + iceTransportPolicy: 'relay', + bundlePolicy: 'max-compat', + rtcpMuxPolicy: 'negotiate', + peerIdentity: 'dude', + certificates: [cert], + iceCandidatePoolSize: 5, }); - -peerConnection.onaddstream = ev => console.log(ev.type); -peerConnection.ondatachannel = ev => console.log(ev.channel); -peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); -peerConnection.onnegotiationneeded = ev => console.log(ev.type); -peerConnection.onopen = ev => console.log(ev.type); -peerConnection.onicecandidate = ev => console.log(ev.type); -peerConnection.onremovestream = ev => console.log(ev.type); -peerConnection.onstatechange = ev => console.log(ev.type); - -peerConnection.createOffer(); -let offer2: Promise = peerConnection.createOffer({ - voiceActivityDetection: true, - iceRestart: false }); -var type: string = RTCSdpType[RTCSdpType.offer]; -var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; -var sessionDescription = new RTCSessionDescription(offer); +// Get/set the configuration +let conf: RTCConfiguration = pc2.getConfiguration(); +pc.setConfiguration(conf); -peerConnection.setRemoteDescription(sessionDescription).then( - () => peerConnection.createAnswer(), - error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp) -); +// Close peer connection +pc2.close(); -var webkitSessionDescription = new webkitRTCSessionDescription(offer); +// Offer/answer flow +let offer: RTCSessionDescriptionInit; +let answer: RTCSessionDescriptionInit; +pc.createOffer({iceRestart: true}) + .then((_offer: RTCSessionDescriptionInit) => offer = _offer); +pc.setLocalDescription(offer); +pc2.setRemoteDescription(offer); +pc2.createAnswer().then((_answer: RTCSessionDescriptionInit) => answer = _answer); +pc2.setLocalDescription(answer); +pc.setRemoteDescription(answer); -// New syntax -voidpromise = peerConnection.setLocalDescription(webkitSessionDescription); +// Event handlers +pc.onnegotiationneeded = ev => console.log(ev.type); +pc.onicecandidate = ev => console.log(ev.candidate); +pc.onicecandidateerror = ev => console.log(ev.errorText); +pc.onsignalingstatechange = ev => console.log(ev.type); +pc.oniceconnectionstatechange = ev => console.log(ev.type); +pc.onicegatheringstatechange = ev => console.log(ev.type); +pc.onconnectionstatechange = ev => console.log(ev.type); +pc.ontrack = ev => console.log(ev.receiver); +pc.ondatachannel = ev => console.log(ev.channel); -// Legacy syntax -peerConnection.setRemoteDescription(webkitSessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log( - "Error setting local description from created answer: " + error + - "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); -}, - error => console.log('Error setting remote description: ' + error + - "; offer.sdp=" + offer.sdp)); - -var mozSessionDescription = new mozRTCSessionDescription(offer); - -peerConnection.setRemoteDescription(mozSessionDescription); - -var wkPeerConnection: webkitRTCPeerConnection = - new webkitRTCPeerConnection(config, constraints); - -let candidate: RTCIceCandidate = { 'candidate': 'foobar' }; -voidpromise = peerConnection.addIceCandidate(candidate); - -var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; -var mediaTrackConstraints: MediaTrackConstraints = mediaTrackConstraintSet; - -wkPeerConnection.getStats(null); - -let mediaStreamTrack: MediaStreamTrack = { - enabled: true, id: - 'id', kind: 'kind', label: 'label', muted: true, onended: () => { }, onmute: () => { }, - onoverconstrained: () => { }, onunmute: () => { }, readonly: true, readyState: 'string', - remote: true, applyConstraints: (): Promise => { return new Promise(() => { }) }, - clone: ():MediaStreamTrack => { return this;}, - getCapabilities: ():MediaTrackCapabilities => { return {latency:0};}, - getConstraints: ():MediaTrackConstraints => { return {}}, - getSettings: ():MediaTrackSettings => { return { latency: 0}}, - stop: () => {}, addEventListener: () => {}, dispatchEvent: (evt:Event):boolean => { return false;}, - removeEventListener: () => {} -}; -wkPeerConnection.getStats(mediaStreamTrack); +// Legacy interface extensions +pc.createOffer( + (sdp: RTCSessionDescription) => console.log(sdp.sdp), + (error: DOMException) => console.log(error.message), + {iceRestart: true} +).then(() => console.log('createOffer complete')); +pc.setLocalDescription( + {type: 'offer', sdp: 'foobar'}, + () => console.log('local description set'), + (error: DOMException) => console.log(error.message) +).then(() => console.log('setLocalDescription complete')); +pc.createAnswer( + (sdp: RTCSessionDescription) => console.log(sdp.sdp), + (error: DOMException) => console.log(error.message) +).then(() => console.log('createAnswer complete')); +pc.setRemoteDescription( + {type: 'answer', sdp: 'foobar'}, + () => console.log('remote description set'), + (error: DOMException) => console.log(error.message) +).then(() => console.log('setRemoteDescription complete')); +pc.addIceCandidate( + {candidate: 'candidate', sdpMid: 'foo', sdpMLineIndex: 1}, + () => console.log('candidate added'), + (error: DOMException) => console.log(error.message) +).then(() => console.log('addIceCandidate complete')); +pc.getStats( + null, + (report: RTCStatsReport) => console.log('got report'), + (error: DOMException) => console.log(error.message) +).then(() => console.log('getStats complete')); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index 1c2ffd4b80..13352158ec 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -1,405 +1,502 @@ -// Type definitions for WebRTC -// Project: http://dev.w3.org/2011/webrtc/ -// Definitions by: Ken Smith +// Type definitions for WebRTC 2016-09-13 +// Project: https://www.w3.org/TR/webrtc/ +// Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // -// W3 Spec: https://www.w3.org/TR/webrtc/#idl-def-RTCIceServer +// W3 Spec: https://www.w3.org/TR/webrtc/ +// +// Note: Commented out definitions clash with definitions in lib.es6.d.ts. I +// still kept them in here though, as sometimes they're more specific than the +// ES6 library ones. -/// +/// -// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string -// enums. -// https://typescript.codeplex.com/discussions/549207 +type EventHandler = (event: Event) => void; -// TODO(2): get Typescript to have union types as WebRtc uses them. -// https://typescript.codeplex.com/workitem/1364 - -// https://www.w3.org/TR/webrtc/#idl-def-RTCIceTransportPolicy -type RTCIceTransportPolicy = 'public' | 'relay' | 'all'; - -// https://www.w3.org/TR/webrtc/#idl-def-RTCBundlePolicy -type RTCBundlePolicy = 'balanced' | 'max-compat' | 'max-bundle'; - -// https://www.w3.org/TR/webrtc/#idl-def-RTCRtcpMuxPolicy -type RTCRtcpMuxPolicy = 'negotiate' | 'require'; - -// https://www.w3.org/TR/webrtc/#idl-def-RTCCertificate -interface RTCCertificate { - expires: number; +// https://www.w3.org/TR/webrtc/#idl-def-rtcofferansweroptions +interface RTCOfferAnswerOptions { + voiceActivityDetection?: boolean; // default = true } -// https://www.w3.org/TR/webrtc/#idl-def-RTCConfiguration -// https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#RTCConfiguration_dictionary -interface RTCConfiguration { - iceServers ?: RTCIceServer[]; // optional according to mozilla docs - iceTransportPolicy ?: RTCIceTransportPolicy; // default = 'all' - bundlePolicy ?: RTCBundlePolicy; // default = 'balanced' - rtcpMuxPolicy ?: RTCRtcpMuxPolicy; // default = 'require' - peerIdentity ?: string; // default = null - certificates ?: RTCCertificate[]; // default is auto-generated - iceCandidatePoolSize ?: number; // default = 0 +// https://www.w3.org/TR/webrtc/#idl-def-rtcofferoptions +interface RTCOfferOptions extends RTCOfferAnswerOptions { + iceRestart?: boolean; // default = false } -declare var RTCConfiguration: { - prototype: RTCConfiguration; - new (): RTCConfiguration; -}; +// https://www.w3.org/TR/webrtc/#idl-def-rtcansweroptions +interface RTCAnswerOptions extends RTCOfferAnswerOptions { +} -// https://www.w3.org/TR/webrtc/#idl-def-RTCIceCredentialType +// https://www.w3.org/TR/webrtc/#idl-def-rtcsdptype +type RTCSdpType = 'offer' | 'pranswer' | 'answer' | 'rollback'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcsessiondescriptioninit +interface RTCSessionDescriptionInit { + type: RTCSdpType; + sdp?: string; // If type is 'rollback', this member can be left undefined. +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcsessiondescription +interface RTCSessionDescription { + readonly type: RTCSdpType; + readonly sdp: string; +} +interface RTCSessionDescriptionStatic { + new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription; // Deprecated +} + +// https://www.w3.org/TR/webrtc/#dom-rtciceprotocol +type RTCIceProtocol = 'udp' | 'tcp'; + +// https://www.w3.org/TR/webrtc/#dom-rtcicecandidatetype +type RTCIceCandidateType = 'host' | 'srflx' | 'prflx' | 'relay'; + +// https://www.w3.org/TR/webrtc/#dom-rtcicetcpcandidatetype +type RTCIceTcpCandidateType = 'active' | 'passive' | 'so'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicecandidateinit +interface RTCIceCandidateInit { + candidate: string; + sdpMid?: string; // default = null + sdpMLineIndex?: number; // default = null +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicecandidate +interface RTCIceCandidate { + readonly candidate: string; + readonly sdpMid?: string; + readonly sdpMLineIndex?: number; + //readonly foundation: string; + //readonly priority: number; + //readonly ip: string; + //readonly protocol: RTCIceProtocol; + //readonly port: number; + //readonly type: RTCIceCandidateType; + //readonly tcpType?: RTCIceTcpCandidateType; + //readonly relatedAddress?: string; + //readonly relatedPort?: number; +} +interface RTCIceCandidateStatic { + new(candidateInitDict: RTCIceCandidateInit): RTCIceCandidate; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicecandidatepair +interface RTCIceCandidatePair { + //local: RTCIceCandidate; + //remote: RTCIceCandidate; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcsignalingstate +type RTCSignalingState = 'stable' | 'have-local-offer' | 'have-remote-offer' | 'have-local-pranswer' | 'have-remote-pranswer'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicegatheringstate +type RTCIceGatheringState = 'new' | 'gathering' | 'complete'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtciceconnectionstate +type RTCIceConnectionState = 'new' | 'checking' | 'connected' | 'completed' | 'failed' | 'disconnected' | 'closed'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcpeerconnectionstate +type RTCPeerConnectionState = 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicecredentialtype type RTCIceCredentialType = 'password' | 'token'; -// https://www.w3.org/TR/webrtc/#idl-def-RTCIceServer +// https://www.w3.org/TR/webrtc/#idl-def-rtciceserver interface RTCIceServer { - urls?: any; - username?: string; - credential?: string; - credentialType?: RTCIceCredentialType; // default = 'password' -} -declare var RTCIceServer: { - prototype: RTCIceServer; - new (): RTCIceServer; -}; - -// moz (Firefox) specific prefixes. -interface mozRTCPeerConnection extends RTCPeerConnection { -} -declare var mozRTCPeerConnection: { - prototype: mozRTCPeerConnection; - new (settings?: RTCConfiguration, - constraints?:RTCMediaConstraints): mozRTCPeerConnection; -}; -// webkit (Chrome) specific prefixes. -interface webkitRTCPeerConnection extends RTCPeerConnection { -} -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new (settings?: RTCConfiguration, - constraints?:RTCMediaConstraints): webkitRTCPeerConnection; -}; - -// For Chrome, look at the code here: -// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 -interface RTCOptionalMediaConstraint { - // When true, will use DTLS/SCTP data channels - DtlsSrtpKeyAgreement?: boolean; - // When true will use Rtp-based data channels (depreicated) - RtpDataChannels?: boolean; + //urls: string | string[]; + username?: string; + credential?: string; + credentialType?: RTCIceCredentialType; // default = 'password' } -// ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. -// http://www.w3.org/TR/2013/WD-webrtc-20130910/ -interface RTCMediaConstraints { - mandatory?: RTCMediaOfferConstraints; - optional?: RTCOptionalMediaConstraint[] +// https://www.w3.org/TR/webrtc/#idl-def-rtcicetransportpolicy +type RTCIceTransportPolicy = 'relay' | 'all'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcbundlepolicy +type RTCBundlePolicy = 'balanced' | 'max-compat' | 'max-bundle'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtcpmuxpolicy +type RTCRtcpMuxPolicy = 'negotiate' | 'require'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicerole +type RTCIceRole = 'controlling' | 'controlled'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicecomponent +type RTCIceComponent = 'RTP' | 'RTCP'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcicetransportstate +type RTCIceTransportState = 'new' | 'checking' | 'connected' | 'completed' | 'failed' | 'disconnected' | 'closed'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtciceparameters +interface RTCIceParameters { + //usernameFragment: string; + //password: string; } -interface RTCMediaOfferConstraints { - OfferToReceiveAudio: boolean; - OfferToReceiveVideo: boolean; +// https://www.w3.org/TR/webrtc/#idl-def-rtcicetransport +interface RTCIceTransport { + //readonly role: RTCIceRole; + //readonly component: RTCIceComponent; + //readonly state: RTCIceTransportState; + readonly gatheringState: RTCIceGatheringState; + getLocalCandidates(): RTCIceCandidate[]; + getRemoteCandidates(): RTCIceCandidate[]; + getSelectedCandidatePair(): RTCIceCandidatePair | null; + getLocalParameters(): RTCIceParameters | null; + getRemoteParameters(): RTCIceParameters | null; + onstatechange: EventHandler; + ongatheringstatechange: EventHandler; + onselectedcandidatepairchange: EventHandler; } -interface RTCSessionDescriptionInit { - type: string; // RTCSdpType; See TODO(1) - sdp: string; +// https://www.w3.org/TR/webrtc/#idl-def-rtcdtlstransportstate +type RTCDtlsTransportState = 'new' | 'connecting' | 'connected' | 'closed' | 'failed'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcdtlstransport +interface RTCDtlsTransport { + readonly transport: RTCIceTransport; + //readonly state: RTCDtlsTransportState; + getRemoteCertificates(): ArrayBuffer[]; + onstatechange: EventHandler; } -interface RTCSessionDescription { - type?: string; // RTCSdpType; See TODO(1) - sdp?: string; +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcodeccapability +interface RTCRtpCodecCapability { + mimeType: string; } -declare var RTCSessionDescription: { - prototype: RTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; - // TODO: Add serializer. - // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) -}; -interface webkitRTCSessionDescription extends RTCSessionDescription{ - type?: string; - sdp?: string; +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpheaderextensioncapability +interface RTCRtpHeaderExtensionCapability { + uri: string; } -declare var webkitRTCSessionDescription: { - prototype: webkitRTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): webkitRTCSessionDescription; -}; -interface mozRTCSessionDescription extends RTCSessionDescription{ - type?: string; - sdp?: string; +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcapabilities +interface RTCRtpCapabilities { + //codecs: RTCRtpCodecCapability[]; + //headerExtensions: RTCRtpHeaderExtensionCapability[]; } -declare var mozRTCSessionDescription: { - prototype: mozRTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): mozRTCSessionDescription; -}; +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtprtxparameters +interface RTCRtpRtxParameters { + //ssrc: number; +} +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpfecparameters +interface RTCRtpFecParameters { + //ssrc: number; +} +// https://www.w3.org/TR/webrtc/#idl-def-rtcdtxstatus +type RTCDtxStatus = 'disabled' | 'enabled'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcprioritytype +type RTCPriorityType = 'very-low' | 'low' | 'medium' | 'high'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpencodingparameters +interface RTCRtpEncodingParameters { + //ssrc: number; + //rtx: RTCRtpRtxParameters; + //fec: RTCRtpFecParameters; + dtx: RTCDtxStatus; + //active: boolean; + //priority: RTCPriorityType; + //maxBitrate: number; + maxFramerate: number; + rid: string; + scaleResolutionDownBy?: number; // default = 1 +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpheaderextensionparameters +interface RTCRtpHeaderExtensionParameters { + //uri: string; + //id: number; + encrypted: boolean; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtcpparameters +interface RTCRtcpParameters { + //cname: string; + //reducedSize: boolean; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcodecparameters +interface RTCRtpCodecParameters { + //payloadType: number; + mimeType: string; + //clockRate: number; + channels?: number; // default = 1 + sdpFmtpLine: string; +} + +type RTCDegradationPreference = 'maintain-framerate' | 'maintain-resolution' | 'balanced'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpparameters +interface RTCRtpParameters { + transactionId: string; + //encodings: RTCRtpEncodingParameters[]; + //headerExtensions: RTCRtpHeaderExtensionParameters[]; + //rtcp: RTCRtcpParameters; + //codecs: RTCRtpCodecParameters[]; + degradationPreference?: RTCDegradationPreference; // default = 'balanced' +} + +// https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource +interface RTCRtpContributingSource { + //readonly timestamp: number; + readonly source: number; + //readonly audioLevel: number | null; + readonly voiceActivityFlag: boolean | null; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcapabilities +interface RTCRtcCapabilities { + codecs: RTCRtpCodecCapability[]; + headerExtensions: RTCRtpHeaderExtensionCapability[]; +} + +// https://www.w3.org/TR/webrtc/#dom-rtcrtpsender +interface RTCRtpSender { + //readonly track?: MediaStreamTrack; + //readonly transport?: RTCDtlsTransport; + //readonly rtcpTransport?: RTCDtlsTransport; + setParameters(parameters?: RTCRtpParameters): Promise; + getParameters(): RTCRtpParameters; + replaceTrack(withTrack: MediaStreamTrack): Promise; +} +interface RTCRtpSenderStatic { + new(): RTCRtpSender; + getCapabilities(kind: string): RTCRtpCapabilities; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtpreceiver +interface RTCRtpReceiver { + //readonly track?: MediaStreamTrack; + //readonly transport?: RTCDtlsTransport; + //readonly rtcpTransport?: RTCDtlsTransport; + getParameters(): RTCRtpParameters; + getContributingSources(): RTCRtpContributingSource[]; +} +interface RTCRtpReceiverStatic { + new(): RTCRtpReceiver; + getCapabilities(kind: string): RTCRtcCapabilities; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiverdirection +type RTCRtpTransceiverDirection = 'sendrecv' | 'sendonly' | 'recvonly' | 'inactive'; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiver +interface RTCRtpTransceiver { + readonly mid: string | null; + readonly sender: RTCRtpSender; + readonly receiver: RTCRtpReceiver; + readonly stopped: boolean; + readonly direction: RTCRtpTransceiverDirection; + setDirection(direction: RTCRtpTransceiverDirection): void; + stop(): void; + setCodecPreferences(codecs: RTCRtpCodecCapability[]): void; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiverinit +interface RTCRtpTransceiverInit { + direction?: RTCRtpTransceiverDirection; // default = 'sendrecv' + streams: MediaStream[]; + sendEncodings: RTCRtpEncodingParameters[]; +} + +// https://www.w3.org/TR/webrtc/#dom-rtccertificate +interface RTCCertificate { + readonly expires: number; + getAlgorithm(): string; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcconfiguration +interface RTCConfiguration { + iceServers?: RTCIceServer[]; + iceTransportPolicy?: RTCIceTransportPolicy; // default = 'all' + bundlePolicy?: RTCBundlePolicy; // default = 'balanced' + rtcpMuxPolicy?: RTCRtcpMuxPolicy; // default = 'require' + peerIdentity?: string; // default = null + certificates?: RTCCertificate[]; + iceCandidatePoolSize?: number; // default = 0 +} + +// Compatibility for older definitions on DefinitelyTyped. +type RTCPeerConnectionConfig = RTCConfiguration; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcsctptransport +interface RTCSctpTransport { + readonly transport: RTCDtlsTransport; + readonly maxMessageSize: number; +} + +// https://www.w3.org/TR/webrtc/#idl-def-rtcdatachannelinit interface RTCDataChannelInit { - ordered ?: boolean; // messages must be sent in-order. - maxPacketLifeTime ?: number; // unsigned short - maxRetransmits ?: number; // unsigned short - protocol ?: string; // default = '' - negotiated ?: boolean; // default = false; - id ?: number; // unsigned short + ordered?: boolean; // default = true + maxPacketLifeTime?: number; + maxRetransmits?: number; + protocol?: string; // default = '' + negotiated?: boolean; // default = false + id?: number; } -// TODO(1) -declare enum RTCSdpType { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype - 'offer', - 'pranswer', - 'answer' -} +// https://www.w3.org/TR/webrtc/#idl-def-rtcdatachannelstate +type RTCDataChannelState = 'connecting' | 'open' | 'closing' | 'closed'; -interface RTCMessageEvent { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message - // At present, this can be an: ArrayBuffer, a string, or a Blob. - // See TODO(2) - data: any; -} - -// TODO(1) -declare enum RTCDataChannelState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState - 'connecting', - 'open', - 'closing', - 'closed' -} +// https://www.w3.org/TR/websockets/#dom-websocket-binarytype +type RTCBinaryType = 'blob' | 'arraybuffer'; +// https://www.w3.org/TR/webrtc/#idl-def-rtcdatachannel interface RTCDataChannel extends EventTarget { - label: string; - reliable: boolean; - readyState: string; // RTCDataChannelState; see TODO(1) - bufferedAmount: number; - binaryType: string; + readonly label: string; + readonly ordered: boolean; + readonly maxPacketLifeTime: number | null; + readonly maxRetransmits: number | null; + readonly protocol: string; + readonly negotiated: boolean; + readonly id: number; + readonly readyState: RTCDataChannelState; + readonly bufferedAmount: number; + bufferedAmountLowThreshold: number; + binaryType: RTCBinaryType; - onopen: (event: Event) => void; - onerror: (event: Event) => void; - onclose: (event: Event) => void; - onmessage: (event: RTCMessageEvent) => void; + close(): void; + send(data: string | Blob | ArrayBuffer | ArrayBufferView): void; - close(): void; - - send(data: string): void ; - send(data: ArrayBuffer): void; - send(data: ArrayBufferView): void; - send(data: Blob): void; -} -declare var RTCDataChannel: { - prototype: RTCDataChannel; - new (): RTCDataChannel; -}; - -// https://www.w3.org/TR/webrtc/#rtcdatachannelevent -interface RTCDataChannelEvent extends Event { - channel: RTCDataChannel; -} -declare var RTCDataChannelEvent: { - prototype: RTCDataChannelEvent; - new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; -}; - -interface RTCIceCandidateEvent extends Event { - candidate: RTCIceCandidate; + onopen: EventHandler; + onmessage: (event: MessageEvent) => void; + onbufferedamountlow: EventHandler; + onerror: (event: ErrorEvent) => void; + onclose: EventHandler; } -interface RTCMediaStreamEvent extends Event { - stream: MediaStream; +// https://www.w3.org/TR/webrtc/#h-rtctrackevent +interface RTCTrackEvent extends Event { + readonly receiver: RTCRtpReceiver; + readonly track: MediaStreamTrack; + readonly streams: MediaStream[]; + readonly transceiver: RTCRtpTransceiver; } -interface EventInit { +// https://www.w3.org/TR/webrtc/#h-rtcpeerconnectioniceevent +interface RTCPeerConnectionIceEvent extends Event { + readonly candidate: RTCIceCandidate | null; + readonly url: string; } -interface RTCDataChannelEventInit extends EventInit { - channel: RTCDataChannel; +// https://www.w3.org/TR/webrtc/#h-rtcpeerconnectioniceerrorevent +interface RTCPeerConnectionIceErrorEvent extends Event { + readonly hostCandidate: string; + readonly url: string; + readonly errorCode: number; + readonly errorText: string; } -interface RTCVoidCallback { - (): void; -} -interface RTCSessionDescriptionCallback { - (sdp: RTCSessionDescription): void; -} -interface RTCPeerConnectionErrorCallback { - (errorInformation: DOMError): void; +// https://www.w3.org/TR/webrtc/#h-rtcdatachannelevent +interface RTCDataChannelEvent { + readonly channel: RTCDataChannel; } -// TODO(1) -declare enum RTCIceGatheringState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum - 'new', - 'gathering', - 'complete' +// https://www.w3.org/TR/webrtc/#idl-def-rtcsessiondescriptioncallback +// Deprecated! +type RTCSessionDescriptionCallback = (sdp: RTCSessionDescription) => void; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcpeerconnectionerrorcallback +// Deprecated! +type RTCPeerConnectionErrorCallback = (error: DOMException) => void; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcstatscallback +// Deprecated! +type RTCStatsCallback = (report: RTCStatsReport) => void; + +// https://www.w3.org/TR/webrtc/#idl-def-rtcpeerconnection +interface RTCPeerConnection extends EventTarget { + createOffer(options?: RTCOfferOptions): Promise; + createAnswer(options?: RTCAnswerOptions): Promise; + + setLocalDescription(description: RTCSessionDescriptionInit): Promise; + readonly localDescription: RTCSessionDescription | null; + readonly currentLocalDescription: RTCSessionDescription | null; + readonly pendingLocalDescription: RTCSessionDescription | null; + + setRemoteDescription(description: RTCSessionDescriptionInit): Promise; + readonly remoteDescription: RTCSessionDescription | null; + readonly currentRemoteDescription: RTCSessionDescription | null; + readonly pendingRemoteDescription: RTCSessionDescription | null; + + addIceCandidate(candidate?: RTCIceCandidateInit | RTCIceCandidate): Promise; + + readonly signalingState: RTCSignalingState; + readonly iceGatheringState: RTCIceGatheringState; + readonly iceConnectionState: RTCIceConnectionState; + readonly connectionState: RTCPeerConnectionState; + readonly canTrickleIceCandidates?: boolean | null; + + getConfiguration(): RTCConfiguration; + setConfiguration(configuration: RTCConfiguration): void; + close(): void; + + onnegotiationneeded: EventHandler; + onicecandidate: (event: RTCPeerConnectionIceEvent) => void; + onicecandidateerror: (event: RTCPeerConnectionIceErrorEvent) => void; + onsignalingstatechange: EventHandler; + oniceconnectionstatechange: EventHandler; + onicegatheringstatechange: EventHandler; + onconnectionstatechange: EventHandler; + + // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions + getSenders(): RTCRtpSender[]; + getReceivers(): RTCRtpReceiver[]; + getTransceivers(): RTCRtpTransceiver[]; + addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender; + removeTrack(sender: RTCRtpSender): void; + addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver; + ontrack: (event: RTCTrackEvent) => void; + + // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions-1 + readonly sctp: RTCSctpTransport | null; + createDataChannel(label: string | null, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + ondatachannel: (event: RTCDataChannelEvent) => void; + + // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions-2 + getStats(selector?: MediaStreamTrack | null): Promise; + + // Extension: https://www.w3.org/TR/webrtc/#legacy-interface-extensions + // Deprecated! + createOffer(successCallback: RTCSessionDescriptionCallback, + failureCallback: RTCPeerConnectionErrorCallback, + options?: RTCOfferOptions): Promise; + setLocalDescription(description: RTCSessionDescriptionInit, + successCallback: () => void, + failureCallback: RTCPeerConnectionErrorCallback): Promise; + createAnswer(successCallback: RTCSessionDescriptionCallback, + failureCallback: RTCPeerConnectionErrorCallback): Promise; + setRemoteDescription(description: RTCSessionDescriptionInit, + successCallback: () => void, + failureCallback: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate, + successCallback: () => void, + failureCallback: RTCPeerConnectionErrorCallback): Promise; + getStats(selector: MediaStreamTrack | null, + successCallback: RTCStatsCallback, + failureCallback: RTCPeerConnectionErrorCallback): Promise; +} +interface RTCPeerConnectionStatic { + new(configuration?: RTCConfiguration): RTCPeerConnection; + readonly defaultIceServers: RTCIceServer[]; + + // Extension: https://www.w3.org/TR/webrtc/#sec.cert-mgmt + generateCertificate(keygenAlgorithm: string): Promise; } -// TODO(1) -declare enum RTCIceConnectionState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState - 'new', - 'checking', - 'connected', - 'completed', - 'failed', - 'disconnected', - 'closed' -} - -// TODO(1) -declare enum RTCSignalingState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState - 'stable', - 'have-local-offer', - 'have-remote-offer', - 'have-local-pranswer', - 'have-remote-pranswer', - 'closed' -} - -// This is based on the current implementation of WebRtc in Chrome; the spec is -// a little unclear on this. -// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport -interface RTCStatsReport { - stat(id: string): string; -} - -interface RTCStatsCallback { - (report: RTCStatsReport): void; -} - -interface RTCOfferAnswerOptions { - voiceActivityDetection ?: boolean; // default = true -} - -interface RTCOfferOptions extends RTCOfferAnswerOptions { - iceRestart ?: boolean; // default = false -} - -interface RTCAnswerOptions extends RTCOfferAnswerOptions { } - -interface RTCPeerConnection { - - createOffer(options?: RTCOfferOptions): Promise; - createOffer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: RTCMediaConstraints): void; // Deprecated - createAnswer(options?: RTCAnswerOptions): Promise; - createAnswer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: RTCMediaConstraints): void; // Deprecated - setLocalDescription(description: RTCSessionDescription | RTCSessionDescriptionInit): Promise; - setLocalDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; // Deprecated - setRemoteDescription(description: RTCSessionDescription | RTCSessionDescriptionInit): Promise; - setRemoteDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; - localDescription: RTCSessionDescription; - remoteDescription: RTCSessionDescription; - signalingState: string; // RTCSignalingState; see TODO(1) - updateIce(configuration?: RTCConfiguration, - constraints?: RTCMediaConstraints): void; - addIceCandidate(candidate: RTCIceCandidate): Promise; - addIceCandidate(candidate:RTCIceCandidate, - successCallback:() => void, - failureCallback:RTCPeerConnectionErrorCallback): void; - iceGatheringState: string; // RTCIceGatheringState; see TODO(1) - iceConnectionState: string; // RTCIceConnectionState; see TODO(1) - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; - createDataChannel(label?: string, - dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: RTCDataChannelEvent) => void; - addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; - removeStream(stream: MediaStream): void; - close(): void; - onnegotiationneeded: (event: Event) => void; - onconnecting: (event: Event) => void; - onopen: (event: Event) => void; - onaddstream: (event: RTCMediaStreamEvent) => void; - onremovestream: (event: RTCMediaStreamEvent) => void; - onstatechange: (event: Event) => void; - oniceconnectionstatechange: (event: Event) => void; - onicecandidate: (event: RTCIceCandidateEvent) => void; - onidentityresult: (event: Event) => void; - onsignalingstatechange: (event: Event) => void; - getStats(selector: MediaStreamTrack | null): Promise; - getStats(selector: MediaStreamTrack | null, - successCallback: RTCStatsCallback, - failureCallback: RTCPeerConnectionErrorCallback): void; -} -declare var RTCPeerConnection: { - prototype: RTCPeerConnection; - new (configuration: RTCConfiguration, - constraints?: RTCMediaConstraints): RTCPeerConnection; -}; - -interface RTCIceCandidate { - candidate: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var RTCIceCandidate: { - prototype: RTCIceCandidate; - new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; -}; - -interface webkitRTCIceCandidate extends RTCIceCandidate { - candidate: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var webkitRTCIceCandidate: { - prototype: webkitRTCIceCandidate; - new (candidateInitDict?: webkitRTCIceCandidate): webkitRTCIceCandidate; -}; - -interface mozRTCIceCandidate extends RTCIceCandidate { - candidate: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var mozRTCIceCandidate: { - prototype: mozRTCIceCandidate; - new (candidateInitDict?: mozRTCIceCandidate): mozRTCIceCandidate; -}; - -interface RTCIceCandidateInit { - candidate: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var RTCIceCandidateInit:{ - prototype: RTCIceCandidateInit; - new (): RTCIceCandidateInit; -}; - -interface PeerConnectionIceEvent { - peer: RTCPeerConnection; - candidate: RTCIceCandidate; -} -declare var PeerConnectionIceEvent: { - prototype: PeerConnectionIceEvent; - new (): PeerConnectionIceEvent; -}; - -interface RTCPeerConnectionConfig { - iceServers: RTCIceServer[]; -} -declare var RTCPeerConnectionConfig: { - prototype: RTCPeerConnectionConfig; - new (): RTCPeerConnectionConfig; -}; - -interface Window{ - RTCPeerConnection: RTCPeerConnection; - webkitRTCPeerConnection: webkitRTCPeerConnection; - mozRTCPeerConnection: mozRTCPeerConnection; - RTCSessionDescription: RTCSessionDescription; - webkitRTCSessionDescription: webkitRTCSessionDescription; - mozRTCSessionDescription: mozRTCSessionDescription; - RTCIceCandidate: RTCIceCandidate; - webkitRTCIceCandidate: webkitRTCIceCandidate; - mozRTCIceCandidate: mozRTCIceCandidate; +declare var RTCPeerConnection: RTCPeerConnectionStatic; +declare var RTCSessionDescription: RTCSessionDescriptionStatic; +declare var RTCIceCandidate: RTCIceCandidateStatic; +//declare var RTCRtpSender: RTCRtpSenderStatic; +//declare var RTCRtpReceiver: RTCRtpReceiverStatic; +interface Window { + RTCPeerConnection: RTCPeerConnectionStatic; + RTCSessionDescription: RTCSessionDescriptionStatic; + RTCIceCandidate: RTCIceCandidateStatic; + RTCRtpSender: RTCRtpSenderStatic; + RTCRtpReceiver: RTCRtpReceiverStatic; } diff --git a/webrtc/readme.md b/webrtc/readme.md index fed66b04ee..05ab9f1b77 100644 --- a/webrtc/readme.md +++ b/webrtc/readme.md @@ -1,14 +1,14 @@ # WebRTC Definition Notes -## The WebRTC specification +## The WebRTC specification -The WebRTC specification is currently a work in progress, but it has been implemented at a basic level in recent versions of Chrome, Opera and (to a lesser extent) Firefox. -The latest version of the specification can be found at http://dev.w3.org/2011/webrtc/editor/webrtc.html. +The WebRTC specification is currently a work in progress, but it has been +implemented at a basic level in recent versions of Chrome, Opera and (to a +lesser extent) Firefox. The latest version of the specification can be found +at https://www.w3.org/TR/webrtc/. -This particular set of definitions has been annotated with the vendor-specific prefixes for Chrome (e.g., `webitkit`), -but anyone who wants, feel free to add the Mozilla-specific prefixes. +This particular set of definitions does not use any vendor-specific prefixes. +Instead, you should probably use [adapter.js](https://github.com/webrtc/adapter). -### Adding the reference to your project - - - \ No newline at end of file +The definitions track the currently published working draft. Deprecated +features are dropped. From e1b8d6829ccfc5f7e658dfd2e46d36353ad86218 Mon Sep 17 00:00:00 2001 From: Ionut Costica Date: Wed, 2 Nov 2016 16:04:21 +0200 Subject: [PATCH 028/131] add deep-assign (#12353) * add deep-assign Add type definitions for https://github.com/sindresorhus/deep-assign * fix(tsconfig): Set strictNullChecks to true --- deep-assign/deep-assign-tests.ts | 10 +++++ deep-assign/index.d.ts | 77 ++++++++++++++++++++++++++++++++ deep-assign/tsconfig.json | 19 ++++++++ 3 files changed, 106 insertions(+) create mode 100644 deep-assign/deep-assign-tests.ts create mode 100644 deep-assign/index.d.ts create mode 100644 deep-assign/tsconfig.json diff --git a/deep-assign/deep-assign-tests.ts b/deep-assign/deep-assign-tests.ts new file mode 100644 index 0000000000..f38a1fc378 --- /dev/null +++ b/deep-assign/deep-assign-tests.ts @@ -0,0 +1,10 @@ +import * as deepAssign from 'deep-assign'; + +deepAssign({a: 1}); +deepAssign({a: 1}, {b: 2}); +deepAssign({a: 1, b: {c: 2}}, {b: {e: 33}, x: 11}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}, {g: 7}); diff --git a/deep-assign/index.d.ts b/deep-assign/index.d.ts new file mode 100644 index 0000000000..46d4cf09f2 --- /dev/null +++ b/deep-assign/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for clone 0.1.11 +// Project: https://github.com/sindresorhus/deep-assign +// Definitions by: Ionut Costica +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Pretty much just returns the target object + * @param target Base object + */ +declare function deepAssign(target: T): T; +/** + * Deeply assigns all the properties of the source object to the + * target object + * @param target Base object + * @param source Extending object + */ +declare function deepAssign(target: T, source: U): T & U; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + */ +declare function deepAssign(target: T, source1: U, source2: V): T & U & V; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X): T & U & V & W & X; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + * @param source5 Fifth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X, source5: Y): T & U & V & W & X & Y; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + * @param source5 Fifth extending object + * @param source6 Sixth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X, source5: Y, source6: Z): T & U & V & W & X & Y & Z; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param sources Extending objects + */ +declare function deepAssign(target: any, ...sources: any[]): any; + +declare namespace deepAssign {} +export = deepAssign; diff --git a/deep-assign/tsconfig.json b/deep-assign/tsconfig.json new file mode 100644 index 0000000000..5f80a3df8f --- /dev/null +++ b/deep-assign/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deep-assign-tests.ts" + ] +} From 59a23e55da1ef5e9a262094f5fffab10239944d7 Mon Sep 17 00:00:00 2001 From: Jeffery Grajkowski Date: Wed, 2 Nov 2016 07:15:10 -0700 Subject: [PATCH 029/131] Types 2.0 cbor (#12355) * Types 2.0 cbor * Respond to reviewer feedback. --- cbor/cbor-tests.ts | 65 ++++++++++++++++++++++++++++++++++++++++++++++ cbor/index.d.ts | 36 +++++++++++++++++++++++++ cbor/tsconfig.json | 19 ++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 cbor/cbor-tests.ts create mode 100644 cbor/index.d.ts create mode 100644 cbor/tsconfig.json diff --git a/cbor/cbor-tests.ts b/cbor/cbor-tests.ts new file mode 100644 index 0000000000..4fb153956a --- /dev/null +++ b/cbor/cbor-tests.ts @@ -0,0 +1,65 @@ +/// +/// + +import cbor = require('cbor'); +import assert = require('assert'); +import fs = require('fs'); + +var encoded = cbor.encode(true); // returns +cbor.decodeFirst(encoded, function(error, obj) { + // error != null if there was an error + // obj is the unpacked object + assert.ok(obj === true); +}); + +// Use integers as keys? +var m = new Map(); +m.set(1, 2); +encoded = cbor.encode(m); // + +var d = new cbor.Decoder(); +d.on('data', function(obj: any) { + console.log(obj); +}); + +var s = fs.createReadStream('foo'); +s.pipe(d); + +var d2 = new cbor.Decoder({ input: '00', encoding: 'hex' }); +d.on('data', function(obj: any) { + console.log(obj); +}); + +try { + console.log(cbor.decodeFirstSync('02')); // 2 + console.log(cbor.decodeAllSync('0202')); // [2, 2] +} catch (e) { + // throws on invalid input +} + +class Bar { + three: number; + constructor() { + this.three = 3; + } +} +const enc = new cbor.Encoder() +enc.addSemanticType(Bar, (encoder, b) => { + encoder.pushAny(b.three); +}) + +class Foo { + one: number; + two: string; +} +const d3 = new cbor.Decoder({ + tags: { + 64000: (val) => { + // check val to make sure it's an Array as expected, etc. + const foo = new Foo(); + foo.one = val[0]; + foo.two = val[1]; + return foo; + } + } +}) diff --git a/cbor/index.d.ts b/cbor/index.d.ts new file mode 100644 index 0000000000..897b6f0629 --- /dev/null +++ b/cbor/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for cbor 2.0.2 +// Project: https://github.com/hildjj/node-cbor +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import stream = require("stream"); + +export function decode(input: Buffer | string): any; +export function decodeAll(input: Buffer | string, callback: (error: any, objs: any[]) => void): void; +export function decodeAllSync(input: Buffer | string): any[]; +export function decodeFirst(input: Buffer | string, callback: (error: any, obj: any) => void): void; +export function decodeFirstSync(input: Buffer | string): any; +export function encode(input: any): Buffer; + +export class Decoder extends stream.Transform { + constructor(params?: { + input?: Buffer | string; + encoding?: string; + tags?: {[tag: number]: (val: any[]) => any} + }); +} + +export class Encoder extends stream.Transform { + constructor(); + addSemanticType(type: new (...args: any[]) => T, encodeFunction: (encoder: Encoder, t: T) => void): void; + pushAny(input: any): void; +} + +export namespace leveldb { + export function decode(input: Buffer | string): any[]; + export function encode(input: any): Buffer; + export const buffer: boolean; + export const name: string; +} diff --git a/cbor/tsconfig.json b/cbor/tsconfig.json new file mode 100644 index 0000000000..79e9a54ef0 --- /dev/null +++ b/cbor/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cbor-tests.ts" + ] +} From 68f01f1244f488681cd6ab04d40b892025813ca4 Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Wed, 2 Nov 2016 07:21:02 -0700 Subject: [PATCH 030/131] Update missing ASTNode.tagName in parse5 (#12424) --- parse5/index.d.ts | 1 + parse5/parse5-tests.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/parse5/index.d.ts b/parse5/index.d.ts index 036018cb6a..34d8d80946 100644 --- a/parse5/index.d.ts +++ b/parse5/index.d.ts @@ -59,6 +59,7 @@ export interface ASTNode { namespaceURI?: string; parentNode?: ASTNode; nodeName: string; + tagName?: string; quirksMode?: boolean; value?: string; __location: LocationInfo | ElementLocationInfo; diff --git a/parse5/parse5-tests.ts b/parse5/parse5-tests.ts index 5657ac5611..9236f33d5f 100644 --- a/parse5/parse5-tests.ts +++ b/parse5/parse5-tests.ts @@ -58,6 +58,7 @@ fragment = parse5.parseFragment('
', {locationInfo: true}); fragment.quirksMode = true; fragment.namespaceURI = ''; fragment.nodeName = ''; +fragment.tagName = ''; fragment.value = ''; fragment.data = ''; fragment = fragment.childNodes[0]; From 35b9ebbe6ed7177af5a3e291196d03d9bc02ba1d Mon Sep 17 00:00:00 2001 From: Caleb Meredith Date: Wed, 2 Nov 2016 10:30:19 -0400 Subject: [PATCH 031/131] Update types-2.0 GraphQL definitions (#12417) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I’m not sure what the exact procedure is for updating types in the `types-2.0` branch, but there’s been some work in the `master` copy of the GraphQL types. This PR updates these types to the most recent version from `master` so that the changes can be available through `@types/graphql`. --- graphql/index.d.ts | 927 ++++++++++++++++++++++++++++----------------- 1 file changed, 586 insertions(+), 341 deletions(-) diff --git a/graphql/index.d.ts b/graphql/index.d.ts index b441fbc204..c7310ab3cc 100644 --- a/graphql/index.d.ts +++ b/graphql/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for graphql v0.7.0 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang +// Definitions by: TonyYang , Caleb Meredith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************* @@ -19,92 +19,11 @@ declare module "graphql" { // Create and operate on GraphQL type definitions and schema. - export { - GraphQLSchema, - - // Definitions - GraphQLScalarType, - GraphQLObjectType, - GraphQLInterfaceType, - GraphQLUnionType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLList, - GraphQLNonNull, - GraphQLDirective, - - // "Enum" of Type Kinds - TypeKind, - - // "Enum" of Directive Locations - DirectiveLocation, - - // Scalars - GraphQLInt, - GraphQLFloat, - GraphQLString, - GraphQLBoolean, - GraphQLID, - - // Built-in Directives defined by the Spec - specifiedDirectives, - GraphQLIncludeDirective, - GraphQLSkipDirective, - GraphQLDeprecatedDirective, - - // Constant Deprecation Reason - DEFAULT_DEPRECATION_REASON, - - // Meta-field definitions. - SchemaMetaFieldDef, - TypeMetaFieldDef, - TypeNameMetaFieldDef, - - // GraphQL Types for introspection. - __Schema, - __Directive, - __DirectiveLocation, - __Type, - __Field, - __InputValue, - __EnumValue, - __TypeKind, - - // Predicates - isType, - isInputType, - isOutputType, - isLeafType, - isCompositeType, - isAbstractType, - - // Un-modifiers - getNullableType, - getNamedType, - } from 'graphql/type'; + export * from 'graphql/type'; // Parse and operate on GraphQL language source files. - export { - Source, - getLocation, - - // Parse - parse, - parseValue, - parseType, - - // Print - print, - - // Visit - visit, - visitInParallel, - visitWithTypeInfo, - Kind, - TokenKind, - BREAK, - } from 'graphql/language'; + export * from 'graphql/language'; // Execute GraphQL queries. @@ -128,7 +47,6 @@ declare module "graphql" { // Utilities for operating on GraphQL type schema and parsed sources. - /* export { // The GraphQL query recommended for a full schema introspection. introspectionQuery, @@ -185,7 +103,6 @@ declare module "graphql" { // Asserts a string is a valid GraphQL name. assertValidName, } from 'graphql/utilities'; - */ } declare module "graphql/graphql" { @@ -256,6 +173,7 @@ declare module "graphql/language" { } declare module "graphql/language/index" { + export * from 'graphql/language/ast'; export { getLocation } from 'graphql/language/location'; import * as Kind from 'graphql/language/kinds'; export { Kind }; @@ -273,7 +191,7 @@ declare module "graphql/language/ast" { * Contains a range of UTF-8 character offsets and token references that * identify the region of the source from which the AST derived. */ - type Location = { + export type Location = { /** * The character offset at which this Node begins. @@ -305,7 +223,7 @@ declare module "graphql/language/ast" { * Represents a range of characters represented by a lexical token * within a Source. */ - type Token = { + export type Token = { /** * The kind of Token. @@ -368,7 +286,7 @@ declare module "graphql/language/ast" { /** * The list of all possible AST node types. */ - type Node = Name + export type Node = Name | Document | OperationDefinition | VariableDefinition @@ -407,7 +325,7 @@ declare module "graphql/language/ast" { // Name - type Name = { + export type Name = { kind: 'Name'; loc?: Location; value: string; @@ -415,17 +333,17 @@ declare module "graphql/language/ast" { // Document - type Document = { + export type Document = { kind: 'Document'; loc?: Location; definitions: Array; } - type Definition = OperationDefinition + export type Definition = OperationDefinition | FragmentDefinition | TypeSystemDefinition // experimental non-spec addition. - type OperationDefinition = { + export type OperationDefinition = { kind: 'OperationDefinition'; loc?: Location; operation: OperationType; @@ -436,9 +354,9 @@ declare module "graphql/language/ast" { } // Note: subscription is an experimental non-spec addition. - type OperationType = 'query' | 'mutation' | 'subscription'; + export type OperationType = 'query' | 'mutation' | 'subscription'; - type VariableDefinition = { + export type VariableDefinition = { kind: 'VariableDefinition'; loc?: Location; variable: Variable; @@ -446,23 +364,23 @@ declare module "graphql/language/ast" { defaultValue?: Value; } - type Variable = { + export type Variable = { kind: 'Variable'; loc?: Location; name: Name; } - type SelectionSet = { + export type SelectionSet = { kind: 'SelectionSet'; loc?: Location; selections: Array; } - type Selection = Field + export type Selection = Field | FragmentSpread | InlineFragment - type Field = { + export type Field = { kind: 'Field'; loc?: Location; alias?: Name; @@ -472,7 +390,7 @@ declare module "graphql/language/ast" { selectionSet?: SelectionSet; } - type Argument = { + export type Argument = { kind: 'Argument'; loc?: Location; name: Name; @@ -482,14 +400,14 @@ declare module "graphql/language/ast" { // Fragments - type FragmentSpread = { + export type FragmentSpread = { kind: 'FragmentSpread'; loc?: Location; name: Name; directives?: Array; } - type InlineFragment = { + export type InlineFragment = { kind: 'InlineFragment'; loc?: Location; typeCondition?: NamedType; @@ -497,7 +415,7 @@ declare module "graphql/language/ast" { selectionSet: SelectionSet; } - type FragmentDefinition = { + export type FragmentDefinition = { kind: 'FragmentDefinition'; loc?: Location; name: Name; @@ -509,7 +427,7 @@ declare module "graphql/language/ast" { // Values - type Value = Variable + export type Value = Variable | IntValue | FloatValue | StringValue @@ -518,49 +436,49 @@ declare module "graphql/language/ast" { | ListValue | ObjectValue - type IntValue = { + export type IntValue = { kind: 'IntValue'; loc?: Location; value: string; } - type FloatValue = { + export type FloatValue = { kind: 'FloatValue'; loc?: Location; value: string; } - type StringValue = { + export type StringValue = { kind: 'StringValue'; loc?: Location; value: string; } - type BooleanValue = { + export type BooleanValue = { kind: 'BooleanValue'; loc?: Location; value: boolean; } - type EnumValue = { + export type EnumValue = { kind: 'EnumValue'; loc?: Location; value: string; } - type ListValue = { + export type ListValue = { kind: 'ListValue'; loc?: Location; values: Array; } - type ObjectValue = { + export type ObjectValue = { kind: 'ObjectValue'; loc?: Location; fields: Array; } - type ObjectField = { + export type ObjectField = { kind: 'ObjectField'; loc?: Location; name: Name; @@ -570,7 +488,7 @@ declare module "graphql/language/ast" { // Directives - type Directive = { + export type Directive = { kind: 'Directive'; loc?: Location; name: Name; @@ -580,23 +498,23 @@ declare module "graphql/language/ast" { // Type Reference - type Type = NamedType + export type Type = NamedType | ListType | NonNullType - type NamedType = { + export type NamedType = { kind: 'NamedType'; loc?: Location; name: Name; }; - type ListType = { + export type ListType = { kind: 'ListType'; loc?: Location; type: Type; } - type NonNullType = { + export type NonNullType = { kind: 'NonNullType'; loc?: Location; type: NamedType | ListType; @@ -604,40 +522,40 @@ declare module "graphql/language/ast" { // Type System Definition - type TypeSystemDefinition = SchemaDefinition + export type TypeSystemDefinition = SchemaDefinition | TypeDefinition | TypeExtensionDefinition | DirectiveDefinition - type SchemaDefinition = { + export type SchemaDefinition = { kind: 'SchemaDefinition'; loc?: Location; directives: Array; operationTypes: Array; } - type OperationTypeDefinition = { + export type OperationTypeDefinition = { kind: 'OperationTypeDefinition'; loc?: Location; operation: OperationType; type: NamedType; } - type TypeDefinition = ScalarTypeDefinition + export type TypeDefinition = ScalarTypeDefinition | ObjectTypeDefinition | InterfaceTypeDefinition | UnionTypeDefinition | EnumTypeDefinition | InputObjectTypeDefinition - type ScalarTypeDefinition = { + export type ScalarTypeDefinition = { kind: 'ScalarTypeDefinition'; loc?: Location; name: Name; directives?: Array; } - type ObjectTypeDefinition = { + export type ObjectTypeDefinition = { kind: 'ObjectTypeDefinition'; loc?: Location; name: Name; @@ -646,7 +564,7 @@ declare module "graphql/language/ast" { fields: Array; } - type FieldDefinition = { + export type FieldDefinition = { kind: 'FieldDefinition'; loc?: Location; name: Name; @@ -655,7 +573,7 @@ declare module "graphql/language/ast" { directives?: Array; } - type InputValueDefinition = { + export type InputValueDefinition = { kind: 'InputValueDefinition'; loc?: Location; name: Name; @@ -664,7 +582,7 @@ declare module "graphql/language/ast" { directives?: Array; } - type InterfaceTypeDefinition = { + export type InterfaceTypeDefinition = { kind: 'InterfaceTypeDefinition'; loc?: Location; name: Name; @@ -672,7 +590,7 @@ declare module "graphql/language/ast" { fields: Array; } - type UnionTypeDefinition = { + export type UnionTypeDefinition = { kind: 'UnionTypeDefinition'; loc?: Location; name: Name; @@ -680,7 +598,7 @@ declare module "graphql/language/ast" { types: Array; } - type EnumTypeDefinition = { + export type EnumTypeDefinition = { kind: 'EnumTypeDefinition'; loc?: Location; name: Name; @@ -688,14 +606,14 @@ declare module "graphql/language/ast" { values: Array; } - type EnumValueDefinition = { + export type EnumValueDefinition = { kind: 'EnumValueDefinition'; loc?: Location; name: Name; directives?: Array; } - type InputObjectTypeDefinition = { + export type InputObjectTypeDefinition = { kind: 'InputObjectTypeDefinition'; loc?: Location; name: Name; @@ -703,13 +621,13 @@ declare module "graphql/language/ast" { fields: Array; } - type TypeExtensionDefinition = { + export type TypeExtensionDefinition = { kind: 'TypeExtensionDefinition'; loc?: Location; definition: ObjectTypeDefinition; } - type DirectiveDefinition = { + export type DirectiveDefinition = { kind: 'DirectiveDefinition'; loc?: Location; name: Name; @@ -1014,29 +932,7 @@ declare module "graphql/type/index" { // GraphQL Schema definition export { GraphQLSchema } from 'graphql/type/schema'; - export { - // Predicates - isType, - isInputType, - isOutputType, - isLeafType, - isCompositeType, - isAbstractType, - - // Un-modifiers - getNullableType, - getNamedType, - - // Definitions - GraphQLScalarType, - GraphQLObjectType, - GraphQLInterfaceType, - GraphQLUnionType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLList, - GraphQLNonNull, - } from 'graphql/type/definition'; + export * from 'graphql/type/definition'; export { // "Enum" of Directive Locations @@ -1098,7 +994,7 @@ declare module "graphql/type/definition" { /** * These are all of the possible kinds of types. */ - type GraphQLType = + export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1108,12 +1004,12 @@ declare module "graphql/type/definition" { GraphQLList | GraphQLNonNull; - function isType(type: any): boolean; + export function isType(type: any): type is GraphQLType; /** * These types may be used as input types for arguments and directives. */ - type GraphQLInputType = + export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | @@ -1125,12 +1021,12 @@ declare module "graphql/type/definition" { GraphQLList >; - function isInputType(type: GraphQLType): boolean; + export function isInputType(type: GraphQLType): type is GraphQLInputType; /** * These types may be used as output types as the result of fields. */ - type GraphQLOutputType = + export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1146,40 +1042,40 @@ declare module "graphql/type/definition" { GraphQLList >; - function isOutputType(type: GraphQLType): boolean; + export function isOutputType(type: GraphQLType): type is GraphQLOutputType; /** * These types may describe types which may be leaf values. */ - type GraphQLLeafType = + export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; - function isLeafType(type: GraphQLType): boolean; + export function isLeafType(type: GraphQLType): type is GraphQLLeafType; /** * These types may describe the parent context of a selection set. */ - type GraphQLCompositeType = + export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; - function isCompositeType(type: GraphQLType): boolean; + export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; /** * These types may describe the parent context of a selection set. */ - type GraphQLAbstractType = + export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; - function isAbstractType(type: GraphQLType): boolean; + export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; /** * These types can all accept null as a value. */ - type GraphQLNullableType = + export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1188,14 +1084,14 @@ declare module "graphql/type/definition" { GraphQLInputObjectType | GraphQLList; - function getNullableType( + export function getNullableType( type: T ): (T & GraphQLNullableType); /** * These named types do not include modifiers like List or NonNull. */ - type GraphQLNamedType = + export type GraphQLNamedType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1203,7 +1099,7 @@ declare module "graphql/type/definition" { GraphQLEnumType | GraphQLInputObjectType; - function getNamedType(type: GraphQLType): GraphQLNamedType + export function getNamedType(type: GraphQLType): GraphQLNamedType /** * Used while defining GraphQL types to allow for circular references in @@ -1245,7 +1141,7 @@ declare module "graphql/type/definition" { toString(): string; } - interface GraphQLScalarTypeConfig { + export interface GraphQLScalarTypeConfig { name: string; description?: string; serialize: (value: any) => TInternal; @@ -1303,7 +1199,7 @@ declare module "graphql/type/definition" { // - interface GraphQLObjectTypeConfig { + export interface GraphQLObjectTypeConfig { name: string; interfaces?: Thunk>; fields: Thunk>; @@ -1311,26 +1207,26 @@ declare module "graphql/type/definition" { description?: string } - type GraphQLTypeResolveFn = ( + export type GraphQLTypeResolveFn = ( value: any, context: any, info: GraphQLResolveInfo ) => GraphQLObjectType; - type GraphQLIsTypeOfFn = ( + export type GraphQLIsTypeOfFn = ( source: any, context: any, info: GraphQLResolveInfo ) => boolean; - type GraphQLFieldResolveFn = ( + export type GraphQLFieldResolveFn = ( source: TSource, args: { [argName: string]: any }, context: any, info: GraphQLResolveInfo ) => any; - interface GraphQLResolveInfo { + export interface GraphQLResolveInfo { fieldName: string; fieldASTs: Array; returnType: GraphQLOutputType; @@ -1343,7 +1239,7 @@ declare module "graphql/type/definition" { variableValues: { [variableName: string]: any }; } - interface GraphQLFieldConfig { + export interface GraphQLFieldConfig { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; resolve?: GraphQLFieldResolveFn; @@ -1351,21 +1247,21 @@ declare module "graphql/type/definition" { description?: string; } - interface GraphQLFieldConfigArgumentMap { + export interface GraphQLFieldConfigArgumentMap { [argName: string]: GraphQLArgumentConfig; } - interface GraphQLArgumentConfig { + export interface GraphQLArgumentConfig { type: GraphQLInputType; defaultValue?: any; description?: string; } - interface GraphQLFieldConfigMap { + export interface GraphQLFieldConfigMap { [fieldName: string]: GraphQLFieldConfig; } - interface GraphQLFieldDefinition { + export interface GraphQLFieldDefinition { name: string; description: string; type: GraphQLOutputType; @@ -1375,14 +1271,14 @@ declare module "graphql/type/definition" { deprecationReason: string; } - interface GraphQLArgument { + export interface GraphQLArgument { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - interface GraphQLFieldDefinitionMap { + export interface GraphQLFieldDefinitionMap { [fieldName: string]: GraphQLFieldDefinition; } @@ -1416,7 +1312,7 @@ declare module "graphql/type/definition" { toString(): string; } - interface GraphQLInterfaceTypeConfig { + export interface GraphQLInterfaceTypeConfig { name: string, fields: Thunk>, /** @@ -1463,7 +1359,7 @@ declare module "graphql/type/definition" { toString(): string; } - interface GraphQLUnionTypeConfig { + export interface GraphQLUnionTypeConfig { name: string, types: Thunk>, /** @@ -1508,23 +1404,23 @@ declare module "graphql/type/definition" { toString(): string; } - interface GraphQLEnumTypeConfig { + export interface GraphQLEnumTypeConfig { name: string; values: GraphQLEnumValueConfigMap; description?: string; } - interface GraphQLEnumValueConfigMap { + export interface GraphQLEnumValueConfigMap { [valueName: string]: GraphQLEnumValueConfig; } - interface GraphQLEnumValueConfig { + export interface GraphQLEnumValueConfig { value?: any; deprecationReason?: string; description?: string; } - interface GraphQLEnumValueDefinition { + export interface GraphQLEnumValueDefinition { name: string; description: string; deprecationReason: string; @@ -1554,36 +1450,36 @@ declare module "graphql/type/definition" { class GraphQLInputObjectType { name: string; description: string; - constructor(config: InputObjectConfig); - getFields(): InputObjectFieldMap; + constructor(config: GraphQLInputObjectTypeConfig); + getFields(): GraphQLInputFieldDefinitionMap; toString(): string; } - interface InputObjectConfig { + export interface GraphQLInputObjectTypeConfig { name: string; - fields: Thunk; + fields: Thunk; description?: string; } - interface InputObjectFieldConfig { + export interface GraphQLInputFieldConfig { type: GraphQLInputType; defaultValue?: any; description?: string; } - interface InputObjectConfigFieldMap { - [fieldName: string]: InputObjectFieldConfig; + export interface GraphQLInputFieldConfigMap { + [fieldName: string]: GraphQLInputFieldConfig; } - interface InputObjectField { + export interface GraphQLInputFieldDefinition { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - interface InputObjectFieldMap { - [fieldName: string]: InputObjectField; + export interface GraphQLInputFieldDefinitionMap { + [fieldName: string]: GraphQLInputFieldDefinition; } /** @@ -2197,194 +2093,543 @@ declare module "graphql/error/syntaxError" { /////////////////////////// // graphql/utilities // /////////////////////////// -// declare module "graphql/utilities/index" { -// // The GraphQL query recommended for a full schema introspection. -// export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; +declare module "graphql/utilities" { + export * from "graphql/utilities/index"; +} -// // Gets the target Operation from a Document -// export { getOperationAST } from 'graphql/utilities/getOperationAST'; +declare module "graphql/utilities/index" { + // The GraphQL query recommended for a full schema introspection. + export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; -// // Build a GraphQLSchema from an introspection result. -// export { buildClientSchema } from 'graphql/utilities/buildClientSchema'; + // Gets the target Operation from a Document + export { getOperationAST } from 'graphql/utilities/getOperationAST'; -// // Build a GraphQLSchema from GraphQL Schema language. -// export { buildASTSchema, buildSchema } from 'graphql/utilities/buildASTSchema'; + // Build a GraphQLSchema from an introspection result. + export { buildClientSchema } from 'graphql/utilities/buildClientSchema'; -// // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. -// export { extendSchema } from 'graphql/utilities/extendSchema'; + // Build a GraphQLSchema from GraphQL Schema language. + export { buildASTSchema, buildSchema } from 'graphql/utilities/buildASTSchema'; -// // Print a GraphQLSchema to GraphQL Schema language. -// export { printSchema, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; + // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. + export { extendSchema } from 'graphql/utilities/extendSchema'; -// // Create a GraphQLType from a GraphQL language AST. -// export { typeFromAST } from 'graphql/utilities/typeFromAST'; + // Print a GraphQLSchema to GraphQL Schema language. + export { printSchema, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; -// // Create a JavaScript value from a GraphQL language AST. -// export { valueFromAST } from 'graphql/utilities/valueFromAST'; + // Create a GraphQLType from a GraphQL language AST. + export { typeFromAST } from 'graphql/utilities/typeFromAST'; -// // Create a GraphQL language AST from a JavaScript value. -// export { astFromValue } from 'graphql/utilities/astFromValue'; + // Create a JavaScript value from a GraphQL language AST. + export { valueFromAST } from 'graphql/utilities/valueFromAST'; -// // A helper to use within recursive-descent visitors which need to be aware of -// // the GraphQL type system. -// export { TypeInfo } from 'graphql/utilities/TypeInfo'; + // Create a GraphQL language AST from a JavaScript value. + export { astFromValue } from 'graphql/utilities/astFromValue'; -// // Determine if JavaScript values adhere to a GraphQL type. -// export { isValidJSValue } from 'graphql/utilities/isValidJSValue'; + // A helper to use within recursive-descent visitors which need to be aware of + // the GraphQL type system. + export { TypeInfo } from 'graphql/utilities/TypeInfo'; -// // Determine if AST values adhere to a GraphQL type. -// export { isValidLiteralValue } from 'graphql/utilities/isValidLiteralValue'; + // Determine if JavaScript values adhere to a GraphQL type. + export { isValidJSValue } from 'graphql/utilities/isValidJSValue'; -// // Concatenates multiple AST together. -// export { concatAST } from 'graphql/utilities/concatAST'; + // Determine if AST values adhere to a GraphQL type. + export { isValidLiteralValue } from 'graphql/utilities/isValidLiteralValue'; -// // Separates an AST into an AST per Operation. -// export { separateOperations } from 'graphql/utilities/separateOperations'; + // Concatenates multiple AST together. + export { concatAST } from 'graphql/utilities/concatAST'; -// // Comparators for types -// export { -// isEqualType, -// isTypeSubTypeOf, -// doTypesOverlap -// } from 'graphql/utilities/typeComparators'; + // Separates an AST into an AST per Operation. + export { separateOperations } from 'graphql/utilities/separateOperations'; -// // Asserts that a string is a valid GraphQL name -// export { assertValidName } from 'graphql/utilities/assertValidName'; -// } + // Comparators for types + export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap + } from 'graphql/utilities/typeComparators'; -// declare module "graphql/utilities/assertValidName" { -// // Helper to assert that provided names are valid. -// function assertValidName(name: string): void; -// } + // Asserts that a string is a valid GraphQL name + export { assertValidName } from 'graphql/utilities/assertValidName'; +} -// declare module "graphql/utilities/astFromValue" { -// import { -// Value, -// //IntValue, -// //FloatValue, -// //StringValue, -// //BooleanValue, -// //EnumValue, -// //ListValue, -// //ObjectValue, -// } from 'graphql/language/ast'; -// import { GraphQLInputType } from 'graphql/type/definition'; +declare module "graphql/utilities/assertValidName" { + // Helper to assert that provided names are valid. + function assertValidName(name: string): void; +} -// /** -// * Produces a GraphQL Value AST given a JavaScript value. -// * -// * A GraphQL type must be provided, which will be used to interpret different -// * JavaScript values. -// * -// * | JSON Value | GraphQL Value | -// * | ------------- | -------------------- | -// * | Object | Input Object | -// * | Array | List | -// * | Boolean | Boolean | -// * | String | String / Enum Value | -// * | Number | Int / Float | -// * | Mixed | Enum Value | -// * -// */ -// // TODO: this should set overloads according to above the table -// export function astFromValue( -// value: any, -// type: GraphQLInputType -// ): Value // Warning: there is a code in bottom: throw new TypeError +declare module "graphql/utilities/astFromValue" { + import { + Value, + //IntValue, + //FloatValue, + //StringValue, + //BooleanValue, + //EnumValue, + //ListValue, + //ObjectValue, + } from 'graphql/language/ast'; + import { GraphQLInputType } from 'graphql/type/definition'; -// } + /** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * + */ + // TODO: this should set overloads according to above the table + export function astFromValue( + value: any, + type: GraphQLInputType + ): Value // Warning: there is a code in bottom: throw new TypeError +} -// declare module "graphql/utilities/buildASTSchema" { -// import { Document } from 'graphql/language/ast'; -// import { Source } from 'graphql/language/source'; -// import { GraphQLSchema } from 'graphql/type/schema'; +declare module "graphql/utilities/buildASTSchema" { + import { Document } from 'graphql/language/ast'; + import { Source } from 'graphql/language/source'; + import { GraphQLSchema } from 'graphql/type/schema'; -// /** -// * This takes the ast of a schema document produced by the parse function in -// * src/language/parser.js. -// * -// * If no schema definition is provided, then it will look for types named Query -// * and Mutation. -// * -// * Given that AST it constructs a GraphQLSchema. The resulting schema -// * has no resolve methods, so execution will use default resolvers. -// */ -// function buildASTSchema(ast: Document): GraphQLSchema; + /** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ + function buildASTSchema(ast: Document): GraphQLSchema; -// /** -// * Given an ast node, returns its string description based on a contiguous -// * block full-line of comments preceding it. -// */ -// function getDescription(node: { loc?: Location }): string; + /** + * Given an ast node, returns its string description based on a contiguous + * block full-line of comments preceding it. + */ + function getDescription(node: { loc?: Location }): string; -// /** -// * A helper function to build a GraphQLSchema directly from a source -// * document. -// */ -// function buildSchema(source: string | Source): GraphQLSchema; -// } + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + function buildSchema(source: string | Source): GraphQLSchema; -// declare module "graphql/utilities/buildClientSchema" { -// import { IntrospectionQuery } from 'graphql/utilities/introspectionQuery'; -// import { GraphQLSchema } from 'graphql/type/schema'; -// /** -// * Build a GraphQLSchema for use by client tools. -// * -// * Given the result of a client running the introspection query, creates and -// * returns a GraphQLSchema instance which can be then used with all graphql-js -// * tools, but cannot be used to execute a query, as introspection does not -// * represent the "resolver", "parse" or "serialize" functions or any other -// * server-internal mechanisms. -// */ -// export function buildClientSchema( -// introspection: IntrospectionQuery -// ): GraphQLSchema; -// } + /** + * Given an ast node, returns its string description based on a contiguous + * block full-line of comments preceding it. + */ + function getDescription(node: { loc?: Location }): string; -// declare module "graphql/utilities/concatAST" { + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + function buildSchema(source: string | Source): GraphQLSchema; +} -// } +declare module "graphql/utilities/buildClientSchema" { + import { IntrospectionQuery } from 'graphql/utilities/introspectionQuery'; + import { GraphQLSchema } from 'graphql/type/schema'; + /** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + */ + function buildClientSchema( + introspection: IntrospectionQuery + ): GraphQLSchema; +} -// declare module "graphql/utilities/extendSchema" { +declare module "graphql/utilities/concatAST" { + import { Document } from 'graphql/language/ast'; + /** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ + function concatAST(asts: Array): Document; +} -// } +declare module "graphql/utilities/extendSchema" { + import { GraphQLSchema } from 'graphql/type/schema'; -// declare module "graphql/utilities/getOperationAST" { + /** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + */ + function extendSchema( + schema: GraphQLSchema, + documentAST: Document + ): GraphQLSchema; +} -// } +declare module "graphql/utilities/getOperationAST" { + import { Document, OperationDefinition } from 'graphql/language/ast'; -// declare module "graphql/utilities/introspectionQuery" { + /** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ + export function getOperationAST( + documentAST: Document, + operationName: string + ): OperationDefinition; +} -// } +declare module "graphql/utilities/introspectionQuery" { + import { DirectiveLocationEnum } from 'graphql/type/directives'; -// declare module "graphql/utilities/isValidJSValue" { + /* + query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + description + locations + args { + ...InputValue + } + } + } + } -// } + fragment FullType on __Type { + kind + name + description + fields(includeDeprecated: true) { + name + description + args { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + description + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } -// declare module "graphql/utilities/isValidLiteralValue" { + fragment InputValue on __InputValue { + name + description + type { ...TypeRef } + defaultValue + } -// } + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + */ + const introspectionQuery: string; -// declare module "graphql/utilities/schemaPrinter" { -// } + interface IntrospectionQuery { + __schema: IntrospectionSchema + } -// declare module "graphql/utilities/separateOperations" { + interface IntrospectionSchema { + queryType: IntrospectionNamedTypeRef; + mutationType?: IntrospectionNamedTypeRef; + subscriptionType?: IntrospectionNamedTypeRef; + types: Array; + directives: Array; + } -// } + type IntrospectionType = + IntrospectionScalarType | + IntrospectionObjectType | + IntrospectionInterfaceType | + IntrospectionUnionType | + IntrospectionEnumType | + IntrospectionInputObjectType; -// declare module "graphql/utilities/typeComparators" { + interface IntrospectionScalarType { + kind: 'SCALAR'; + name: string; + description?: string; + } -// } + interface IntrospectionObjectType { + kind: 'OBJECT'; + name: string; + description?: string; + fields: Array; + interfaces: Array; + } -// declare module "graphql/utilities/typeFromAST" { + interface IntrospectionInterfaceType { + kind: 'INTERFACE'; + name: string; + description?: string; + fields: Array; + possibleTypes: Array; + } -// } + interface IntrospectionUnionType { + kind: 'UNION'; + name: string; + description?: string; + possibleTypes: Array; + } + + interface IntrospectionEnumType { + kind: 'ENUM'; + name: string; + description?: string; + enumValues: Array; + } + + interface IntrospectionInputObjectType { + kind: 'INPUT_OBJECT'; + name: string; + description?: string; + inputFields: Array; + } + + type IntrospectionTypeRef = + IntrospectionNamedTypeRef | + IntrospectionListTypeRef | + IntrospectionNonNullTypeRef + + interface IntrospectionNamedTypeRef { + kind: string; + name: string; + } + + interface IntrospectionListTypeRef { + kind: 'LIST'; + ofType?: IntrospectionTypeRef; + } + + interface IntrospectionNonNullTypeRef { + kind: 'NON_NULL'; + ofType?: IntrospectionTypeRef; + } + + interface IntrospectionField { + name: string; + description?: string; + args: Array; + type: IntrospectionTypeRef; + isDeprecated: boolean; + deprecationReason?: string; + } + + interface IntrospectionInputValue { + name: string; + description?: string; + type: IntrospectionTypeRef; + defaultValue?: string; + } + + interface IntrospectionEnumValue { + name: string; + description?: string; + isDeprecated: boolean; + deprecationReason?: string; + } + + interface IntrospectionDirective { + name: string; + description?: string; + locations: Array; + args: Array; + } +} + +declare module "graphql/utilities/isValidJSValue" { + import { GraphQLInputType } from 'graphql/type/definition'; + + /** + * Given a JavaScript value and a GraphQL type, determine if the value will be + * accepted for that type. This is primarily useful for validating the + * runtime values of query variables. + */ + function isValidJSValue( + value: any, + type: GraphQLInputType + ): Array +} + +declare module "graphql/utilities/isValidLiteralValue" { + import { Value } from 'graphql/language/ast'; + import { GraphQLInputType } from 'graphql/type/definition'; + + /** + * Utility for validators which determines if a value literal AST is valid given + * an input type. + * + * Note that this only validates literal values, variables are assumed to + * provide values of the correct type. + */ + function isValidLiteralValue( + type: GraphQLInputType, + valueAST: Value + ): Array +} + +declare module "graphql/utilities/schemaPrinter" { + import { GraphQLSchema } from 'graphql/type/schema'; + + function printSchema(schema: GraphQLSchema): string; + + function printIntrospectionSchema(schema: GraphQLSchema): string; +} + +declare module "graphql/utilities/separateOperations" { + import { + Document, + OperationDefinition, + } from 'graphql/language/ast'; + + function separateOperations( + documentAST: Document + ): { [operationName: string]: Document } +} + +declare module "graphql/utilities/typeComparators" { + import { + GraphQLType, + GraphQLCompositeType, + GraphQLAbstractType + } from 'graphql/type/definition'; + import { + GraphQLSchema + } from 'graphql/type/schema'; + + /** + * Provided two types, return true if the types are equal (invariant). + */ + function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean; + + /** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + function isTypeSubTypeOf( + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType + ): boolean; + + /** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType + ): boolean; +} + +declare module "graphql/utilities/typeFromAST" { + import { Type } from 'graphql/language/ast'; + import { GraphQLType, GraphQLNullableType } from 'graphql/type/definition'; + import { GraphQLSchema } from 'graphql/type/schema'; + + function typeFromAST( + schema: GraphQLSchema, + inputTypeAST: Type + ): GraphQLType +} declare module "graphql/utilities/TypeInfo" { class TypeInfo { } } -// declare module "graphql/utilities/valueFromAST" { +declare module "graphql/utilities/valueFromAST" { + import { GraphQLInputType } from 'graphql/type/definition'; + import { + Value, + Variable, + ListValue, + ObjectValue + } from 'graphql/language/ast'; -// } + function valueFromAST( + valueAST: Value, + type: GraphQLInputType, + variables?: { + [key: string]: any + } + ): any; +} From b13d495494bc1298f1618aa7c5bd0c24f873f483 Mon Sep 17 00:00:00 2001 From: "Scott(JuJiang)" Date: Wed, 2 Nov 2016 22:41:44 +0800 Subject: [PATCH 032/131] feat: add definition for loader-runner (#12375) * feat: add definition for loader-runner * fix: enable strictNullChecks --- loader-runner/index.d.ts | 35 ++++++++++++++++++++++++++++ loader-runner/loader-runner-tests.ts | 9 +++++++ loader-runner/tsconfig.json | 19 +++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 loader-runner/index.d.ts create mode 100644 loader-runner/loader-runner-tests.ts create mode 100644 loader-runner/tsconfig.json diff --git a/loader-runner/index.d.ts b/loader-runner/index.d.ts new file mode 100644 index 0000000000..102348ec71 --- /dev/null +++ b/loader-runner/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for loader-runner v2.2.0 +// Project: http://github.com/webpack/loader-runner.git +// Definitions by: e-cloud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface Loader { + path: string; + query: string; + request: any; + options: any; + normal: any; + pitch: any; + raw: string; + data: any; + pitchExecuted: boolean; + normalExecuted: boolean; +} + +export function getContext(resource: string): string; + +export interface RunLoaderOption { + resource: string; + loaders: any[]; + context: any; + readResource: (filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void) => void; +} + +export function runLoaders( + options: RunLoaderOption, + callback: (err: NodeJS.ErrnoException, result: any) => any +): void; + + diff --git a/loader-runner/loader-runner-tests.ts b/loader-runner/loader-runner-tests.ts new file mode 100644 index 0000000000..cfdd08f11b --- /dev/null +++ b/loader-runner/loader-runner-tests.ts @@ -0,0 +1,9 @@ +import { runLoaders, getContext, Loader, RunLoaderOption } from 'loader-runner'; + +const option = {} as RunLoaderOption; + +runLoaders(option, function (err, result) { + console.log(err, result); +}); + +getContext('sdlfkjaldfjiojsdf'); diff --git a/loader-runner/tsconfig.json b/loader-runner/tsconfig.json new file mode 100644 index 0000000000..5a8b4508f1 --- /dev/null +++ b/loader-runner/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "loader-runner-tests" + ] +} From 73f8638b309db3c06b78be6f39fed31e6ce73ce1 Mon Sep 17 00:00:00 2001 From: "Scott(JuJiang)" Date: Wed, 2 Nov 2016 22:42:27 +0800 Subject: [PATCH 033/131] feat: add definition for source-list-map (#12378) * feat: add definition for source-list-map * fix: enable strictNullChecks --- source-list-map/index.d.ts | 92 ++++++++++++++++++++++++ source-list-map/source-list-map-tests.ts | 34 +++++++++ source-list-map/tsconfig.json | 19 +++++ 3 files changed, 145 insertions(+) create mode 100644 source-list-map/index.d.ts create mode 100644 source-list-map/source-list-map-tests.ts create mode 100644 source-list-map/tsconfig.json diff --git a/source-list-map/index.d.ts b/source-list-map/index.d.ts new file mode 100644 index 0000000000..c6cfb0ac45 --- /dev/null +++ b/source-list-map/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for source-list-map v0.1.6 +// Project: http://github.com/webpack/source-list-map.git +// Definitions by: e-cloud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class CodeNode { + generatedCode: string; + + constructor(generatedCode: string); + + clone(): CodeNode; + + getGeneratedCode(): string; + + getMappings(mappingsContext?: MappingsContext): string; + + addGeneratedCode(generatedCode: string): void; + + mapGeneratedCode(fn: (code: string) => string): void; +} + +export class MappingsContext { + sources: string[]; + sourcesContent: string[]; + hasSourceContent: boolean; + currentOriginalLine: number; + currentSource: number; + + constructor(); + + ensureSource(source: string, originalSource: string): number; +} + +export class SourceNode { + generatedCode: string; + source: string; + originalSource: string; + startingLine: number; + + constructor(generatedCode: string, source: string, originalSource: string, startingLine?: number); + + clone(): SourceNode; + + getGeneratedCode(): string; + + getMappings(mappingsContext: MappingsContext): string; + + mapGeneratedCode(fn: (code: string) => string): void; +} + +export class SourceListMap { + children: (SourceNode | CodeNode | SourceListMap)[]; + + constructor(generatedCode: (SourceNode | CodeNode | SourceListMap)[]); + constructor( + generatedCode?: string | SourceNode | CodeNode | SourceListMap, + source?: string, + originalSource?: string + ); + + add( + generatedCode: string | CodeNode | SourceNode | SourceListMap, + source?: string, + originalSource?: string + ): void; + + prepend(generatedCode: SourceListMap | SourceNode | CodeNode, source?: string, originalSource?: string): void; + + mapGeneratedCode(fn: (code: string) => string): void; + + toString(): string; + + toStringWithSourceMap(options: { file: any }): { + source: string; + map: { + version: number; + file: any; + sources: string[]; + sourcesContent: string[]; + mappings: string; + }; + }; +} + +export function fromStringWithSourceMap( + code: string, map: { + sources: any; + sourcesContent: any; + mappings: any; + } +): SourceListMap; + diff --git a/source-list-map/source-list-map-tests.ts b/source-list-map/source-list-map-tests.ts new file mode 100644 index 0000000000..75341740be --- /dev/null +++ b/source-list-map/source-list-map-tests.ts @@ -0,0 +1,34 @@ +/// +import * as slm from 'source-list-map'; + +const node = new slm.CodeNode('hello'); + +node.addGeneratedCode('world'); +node.getGeneratedCode(); +node.getMappings(); +node.mapGeneratedCode(function (code) { + if (typeof code === 'string') {} + + return code; +}) + +slm.fromStringWithSourceMap('hello', { + sources: null, + sourcesContent: null, + mappings: null +}); + +const snode = new slm.SourceNode('hi', 'i\'am', 'e-cloud'); +const snode1 = new slm.SourceNode('hi', 'i\'am', 'e-cloud', 1); +snode.getGeneratedCode(); + +const context = new slm.MappingsContext(); +snode.getMappings(context); + +context.ensureSource('hey', 'guy'); + +const map = new slm.SourceListMap('hey', 'sorry', 'to be late'); +const map1 = new slm.SourceListMap([snode, node]); + +map.add('hi', 'every', 'body'); +map.toStringWithSourceMap({ file: 'here' }); diff --git a/source-list-map/tsconfig.json b/source-list-map/tsconfig.json new file mode 100644 index 0000000000..f04d1825ac --- /dev/null +++ b/source-list-map/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "source-list-map-tests.ts" + ] +} From 8b066c852810031aad8e9b3aa3e8dc2308359d72 Mon Sep 17 00:00:00 2001 From: "Scott(JuJiang)" Date: Wed, 2 Nov 2016 22:43:39 +0800 Subject: [PATCH 034/131] feat: add definition for tapable of webpack (#12376) * feat: add definition for tapable of webpack * fix: enable strictNullChecks and adjust tests --- tapable/index.d.ts | 201 +++++++++++++++++++++++++++++++++++++++ tapable/tapable-tests.ts | 43 +++++++++ tapable/tsconfig.json | 19 ++++ 3 files changed, 263 insertions(+) create mode 100644 tapable/index.d.ts create mode 100644 tapable/tapable-tests.ts create mode 100644 tapable/tsconfig.json diff --git a/tapable/index.d.ts b/tapable/index.d.ts new file mode 100644 index 0000000000..4588643c6d --- /dev/null +++ b/tapable/index.d.ts @@ -0,0 +1,201 @@ +// Type definitions for tapable v0.2.4 +// Project: http://github.com/webpack/tapable.git +// Definitions by: e-cloud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare abstract class Tapable { + /** + * Register plugin(s) + * This acts as the same as on() of EventEmitter, for registering a handler/listener to do something when the + * signal/event happens. + * + * @param names a string or an array of strings to generate the id(group name) of plugins + * @param handler a function which provides the plugin functionality * + */ + plugin(names: string, handler: Tapable.Listener): void; + + plugin(names: string[], handler: Tapable.Listener): void; + + /** + * invoke all plugins with this attached. + * This method is just to "apply" plugins' definition, so that the real event listeners can be registered into + * registry. Mostly the `apply` method of a plugin is the main place to place extension logic. + */ + apply(...plugins: Tapable.Plugin[]): void; + + /** + * synchronously applies all registered handlers for target name(event id). + * + * The handlers are called with all the rest arguments. + * + * @param name - plugin group name + * @param args + */ + applyPlugins(name: string, ...args: any[]): void; + + /** + * synchronously applies all registered handlers for target name(event id). + * + * The handlers are called with the return value of the previous handler and all the rest arguments. + * + * `init` is used for the first handler. + * + * return the returned value of the last handler + */ + applyPluginsWaterfall(name: string, init: any, ...args: any[]): any; + + /** + * synchronously applies all registered handlers for target name(event id). + * + * The handlers are called ONLY with the return value of the previous handler. + * + * `init` is used for the first handler. + * + * return the returned value of the last handler + */ + applyPluginsWaterfall0(name: string, init: any): any; + + /** + * synchronously applies all registered handlers for target name(event id). + * + * The handlers are called with all the rest arguments. + * + * If a handler returns something !== undefined, that value is returned and no more handlers will be applied. + */ + applyPluginsBailResult(name: string, ...args: any[]): any; + + /** + * synchronously applies all registered handlers for target name(event id). + * + * The handlers are called with target param + * + * If a handler returns something !== undefined, the value is returned and no more handlers are applied. + * + * Note: the fundamental difference with `{@link applyPluginsBailResult}`, is that, + * `{@link applyPluginsBailResult}` passes the arguments as arguments list for plugins + * while `{@link applyPluginsBailResult1}` passes the arguments as single param(any type) for plugins + */ + applyPluginsBailResult1(name: string, param: any): any; + + /** + * asynchronously applies all registered handlers for target name(event id). + * + * The handlers are called with all the rest arguments + * and a callback function with the signature (err: Error) => void. + * + * The handlers are called in series, one at a time. After all handlers are applied, callback is called. + * + * If any handler invokes the (anonymous)callback with error, no more handlers will be called + * and the real callback is call with that error. + */ + applyPluginsAsync(name: string, ...args: any[]): void; + + /** + * same as `applyPluginsAsync` + * @see applyPluginsAsync + * @alias Tapable.applyPluginsAsync + * @param name + * @param args + */ + applyPluginsAsyncSeries(name: string, ...args: any[]): void; + + /** + * asynchronously applies all registered handlers for target name(event id). + * + * The handlers are called with all the rest arguments + * and a callback function with the signature (...params) => void. + * + * Handlers must invoke the (anonymous)callback, otherwise the series is cut down and real callback won't be + * invoked. + * + * The order is defined by registration order not by speed of the handler function. + * + * If a handler returns something !== undefined, that value is returned and no more handlers will be applied. + */ + applyPluginsAsyncSeriesBailResult(name: string, ...args: any[]): void; + + /** + * asynchronously applies all registered handlers for target name(event id). + * + * @see applyPluginsAsyncSeriesBailResult + * + * Note: the fundamental difference with `{@link applyPluginsAsyncSeriesBailResult}`, is that, + * `{@link applyPluginsAsyncSeriesBailResult}` passes the arguments as arguments list for plugins + * while `{@link applyPluginsAsyncSeriesBailResult1}` passes the arguments as single param(any type) + * and a callback for plugins + */ + applyPluginsAsyncSeriesBailResult1(name: string, param: any, callback: Tapable.CallbackFunction): void; + + /** + * Asynchronously applies all registered handlers for target name(event id). + * + * The handlers are called with the current value and a callback function with the signature (err: Error, + * nextValue: any) => void. + * + * `init` is used for the first handler. The rest handles are called with the value which previous handler uses + * to invoke the (anonymous)callback invoked + * + * After all handlers are applied, callback is called with the last value. + * + * If any handler invokes the (anonymous)callback with error, no more handlers will be called + * and the real callback is call with that error. + */ + applyPluginsAsyncWaterfall(name: string, init: any, callback: Tapable.CallbackFunction): void; + + /** + * applies all registered handlers for target name(event id) in parallel. + * + * The handlers are called with all the rest arguments + * and a callback function with the signature (err?: Error) => void. + * + * The callback function is called when all handlers call the callback without err. + * + * If any handler invokes the callback with err, callback is invoked with this error and the other handlers are + * skipped. + */ + applyPluginsParallel(name: string, ...args: any[]): void; + + /** + * applies all registered handlers for target name(event id) in parallel. + * + * The handlers are called with all the rest arguments + * and a callback function with the signature (currentResult?: []) => void. + * + * Handlers must call the callback. + * + * The first result (either error or value) with is not undefined is passed to the callback. + * + * The order is defined by registration not by speed of the handler function. + */ + applyPluginsParallelBailResult(name: string, ...args: any[]): void; + + /** + * applies all registered handlers for target name(event id) in parallel. + * + * @see applyPluginsParallelBailResult + * + * Note: the fundamental difference with `{@link applyPluginsParallelBailResult}`, is that, + * `{@link applyPluginsParallelBailResult}` passes the arguments as arguments list for plugins + * while `{@link applyPluginsParallelBailResult1}` passes the arguments as single param(any type) + * and a callback for plugins + */ + applyPluginsParallelBailResult1(name: string, param: any, callback: Tapable.CallbackFunction): void; + + static mixin(proto: any): void; +} + +declare namespace Tapable { + interface Listener { + (...args: any[]): void; + } + + interface Plugin { + apply(...args: any[]): void; + } + + interface CallbackFunction { + (err?: Error, result?: any, ...args: any[]): void; + } +} + +export = Tapable diff --git a/tapable/tapable-tests.ts b/tapable/tapable-tests.ts new file mode 100644 index 0000000000..eca641655c --- /dev/null +++ b/tapable/tapable-tests.ts @@ -0,0 +1,43 @@ +/// + +import Tapable = require('tapable'); + +class DllPlugin { + apply(compiler: Compiler) { + compiler.plugin('doSomething', function (...args: string[]) { + console.log(args); + }); + + compiler.plugin(['doSomething', 'doNothing'], function (...args: string[]) { + console.log(args); + }); + } +} + +class Compiler extends Tapable { + constructor(){ + super() + } +} + +const compiler = new Compiler(); + +let callback: Tapable.CallbackFunction = function () { + +}; + +compiler.apply(new DllPlugin()); + +compiler.applyPlugins('doSomething', 'a', 'b'); +compiler.applyPluginsWaterfall('doSomething', 'a', 'b'); +compiler.applyPluginsWaterfall0('doSomething', 'a'); +compiler.applyPluginsBailResult('doSomething', 'a', 'b'); +compiler.applyPluginsBailResult1('doSomething', ['a', 'b']); +compiler.applyPluginsAsync('doSomething', 'a', 'b'); +compiler.applyPluginsAsyncSeries('doSomething', 'a', 'b'); +compiler.applyPluginsAsyncSeriesBailResult('doSomething', 'a', 'b'); +compiler.applyPluginsAsyncSeriesBailResult1('doSomething', 'a', callback); +compiler.applyPluginsAsyncWaterfall('doSomething', 'a', callback); +compiler.applyPluginsParallel('doSomething', 'a', 'b'); +compiler.applyPluginsParallelBailResult('doSomething', 'a', 'b'); +compiler.applyPluginsParallelBailResult1('doSomething', 'a', callback); diff --git a/tapable/tsconfig.json b/tapable/tsconfig.json new file mode 100644 index 0000000000..d17c09d65b --- /dev/null +++ b/tapable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tapable-tests.ts" + ] +} From 15ba795ddb4e2d6efc7f536b622a19fb55bbe007 Mon Sep 17 00:00:00 2001 From: Artur Eshenbrener Date: Wed, 2 Nov 2016 18:48:15 +0400 Subject: [PATCH 035/131] sequester: add typings (#12343) * sequester: add typings https://github.com/bigeasy/sequester https://www.npmjs.com/package/sequester * Change tsconfig files section --- sequester/index.d.ts | 17 +++++++++++++++++ sequester/sequester-tests.ts | 13 +++++++++++++ sequester/tsconfig.json | 19 +++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 sequester/index.d.ts create mode 100644 sequester/sequester-tests.ts create mode 100644 sequester/tsconfig.json diff --git a/sequester/index.d.ts b/sequester/index.d.ts new file mode 100644 index 0000000000..bb0c118b5f --- /dev/null +++ b/sequester/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for sequester 1.0.0 +// Project: https://github.com/bigeasy/sequester +// Definitions by: Artur Eshenbrener +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type Callback = () => void; + +export interface Lock { + share(cb: Callback): void; + exclude(cb: Callback): void; + count: number; + dispose(): void; + unlock(): void; + downgrade(): void; +} + +export function createLock(): Lock; diff --git a/sequester/sequester-tests.ts b/sequester/sequester-tests.ts new file mode 100644 index 0000000000..52873c67f3 --- /dev/null +++ b/sequester/sequester-tests.ts @@ -0,0 +1,13 @@ +import * as sequester from "sequester"; + +function cb() {}; + +{ + const lock = sequester.createLock(); + lock.share(cb); + lock.exclude(cb); + const a: number = lock.count; + lock.unlock(); + lock.downgrade(); + lock.dispose(); +} diff --git a/sequester/tsconfig.json b/sequester/tsconfig.json new file mode 100644 index 0000000000..0503a93628 --- /dev/null +++ b/sequester/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sequester-tests.ts" + ] +} From a1383223f00e01dd9bb3928f2d3f3cbe236780d2 Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 2 Nov 2016 10:49:20 -0400 Subject: [PATCH 036/131] Implement xml-js (#12433) --- xml-js/index.d.ts | 82 ++++++++++++++++++++++++++++++++++++++++++ xml-js/tsconfig.json | 19 ++++++++++ xml-js/xml-js-tests.ts | 48 +++++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 xml-js/index.d.ts create mode 100644 xml-js/tsconfig.json create mode 100644 xml-js/xml-js-tests.ts diff --git a/xml-js/index.d.ts b/xml-js/index.d.ts new file mode 100644 index 0000000000..eb89067c86 --- /dev/null +++ b/xml-js/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for xml-js 0.9.6 +// Project: https://github.com/nashwaan/xml-js +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ElementCompact { + [key: string]: any + _attributes?: { + [key: string]: number | number + } + _cdata?: string | number + _comment?: string | number + _declaration?: { + _attributes?: { + version?: string | number + encoding?: string | number + } + } + _text?: string | number +} + +export interface Element { + attributes?: { + [key: string]: string | number + } + cdata?: string | number + comment?: string | number + declaration?: { + attributes?: { + version: string | number + encoding: string | number + } + } + elements?: Array + text?: string | number + type?: string | number + name?: string | number +} + +declare namespace Options { + interface XML2JS extends ChangingKeyNames, IgnoreOptions { + compact?: boolean + spaces?: number | string + trim?: boolean + sanitize?: boolean + nativeType?: boolean + addParent?: boolean + alwaysChildren?: boolean + } + + interface JS2XML extends ChangingKeyNames, IgnoreOptions { + spaces?: number | string + compact?: boolean + fullTagEmptyElement?: boolean + } + + interface IgnoreOptions { + ignoreDeclaration?: boolean + ignoreAttributes?: boolean + ignoreComment?: boolean + ignoreCdata?: boolean + ignoreText?: boolean + } + + interface ChangingKeyNames { + declarationKey?: string + attributesKey?: string + textKey?: string + cdataKey?: string + commentKey?: string + parentKey?: string + typeKey?: string + nameKey?: string + elementsKey?: string + } +} + +export function js2xml(json: Element | ElementCompact, options?: Options.JS2XML): string; +export function json2xml(json: Element | ElementCompact, options?: Options.JS2XML): string; +export function xml2json(xml: string, options?: Options.XML2JS): any; +export function xml2js(xml: string, options?: Options.XML2JS): any; + diff --git a/xml-js/tsconfig.json b/xml-js/tsconfig.json new file mode 100644 index 0000000000..5880b2f31d --- /dev/null +++ b/xml-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xml-js-tests.ts" + ] +} diff --git a/xml-js/xml-js-tests.ts b/xml-js/xml-js-tests.ts new file mode 100644 index 0000000000..d437ee14f4 --- /dev/null +++ b/xml-js/xml-js-tests.ts @@ -0,0 +1,48 @@ +import { Element, ElementCompact } from 'xml-js' +import * as convert from 'xml-js' + +// Declaration +const declarationCompact1: ElementCompact = { _declaration: { _attributes: { version: 2 } }}; +const declarationCompact2: ElementCompact = { _declaration: { _attributes: { version: '1.0', encoding: 'utf-8' }}}; +const declaration1: Element = { declaration: { }}; +const declaration2: Element = { declaration: { attributes: { version: '1.0', encoding: 'utf-8' }}}; + +// Comment +const commentCompact: ElementCompact = { _comment : 'Hello, World!' }; +const comment: Element = { elements: [{ type: 'comment', comment: 'Hello, World!' }]}; + +// CDATA +const cdataCompact: ElementCompact = { _cdata: '' }; +const cdata: Element = { elements : [{ type: 'cdata', cdata: '' }]}; + +// Element +const elementCompact1: ElementCompact = { a: {} }; +const element1: Element = { elements:[{ type: 'element', name: 'a' }]}; + +const elementCompact2: ElementCompact = { a: { _attributes: { x: '1.234', y:'It\'s' }}}; +const element2: Element = { elements: [{ type: 'element', name: 'a', attributes: { x: '1.234', y: 'It\'s' }}]}; + +const elementCompact3: ElementCompact = { a: { _text: ' Hi ' }}; +const element3: Element = { elements:[{ type: 'element', name: 'a', elements: [{ type: 'text', text: ' Hi ' }]}]}; + +const elementCompact4: ElementCompact = { a: {}, b: {} }; +const element4: Element = { elements:[{ type: 'element', name: 'a' }, { type: 'element', name: 'b' }]}; + +const elementCompact5: ElementCompact = { a: { b: {} }}; +const element5: Element = { elements: [{ type: 'element', name: 'a', elements: [{ type: 'element', name: 'b' }]}]}; + +// xml2json +const xml = ` + + + Happy + Work + Play +`; +convert.xml2json(xml, { compact: true, spaces: 4 }); +convert.xml2json(xml, { compact: false }); + +// json2xml +convert.json2xml({ a: {} }, { compact: true, spaces: 4 }); +convert.json2xml({ elements:[{ type: 'element', name: 'a' }]}, { compact: false }); + From 00740e74f7766e91d59393822b15cf80dc4083b3 Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Wed, 2 Nov 2016 20:21:00 +0530 Subject: [PATCH 037/131] Types for code v4.0.0 (#12402) * Initial commit for code v4.0.0 * Merge upstream, remove module declaration * Fix include alias signature, fix typos * Add stronger types to tests and run linter --- code/code-tests.ts | 162 ++++++++++++++++++++++++++++++++++++++ code/index.d.ts | 188 +++++++++++++++++++++++++++++++++++++++++++++ code/tsconfig.json | 19 +++++ 3 files changed, 369 insertions(+) create mode 100644 code/code-tests.ts create mode 100644 code/index.d.ts create mode 100644 code/tsconfig.json diff --git a/code/code-tests.ts b/code/code-tests.ts new file mode 100644 index 0000000000..ea956c6c2c --- /dev/null +++ b/code/code-tests.ts @@ -0,0 +1,162 @@ +import { expect, settings, fail, count, incomplete, thrownAt } from "code"; + +expect(10).to.be.above(5); +expect("abc").to.be.a.string(); +expect([1, 2]).to.be.an.array(); +expect(20).to.be.at.least(20); +expect("abc").to.have.length(3); +expect("abc").to.be.a.string().and.contain(["a", "b"]); +expect(6).to.be.in.range(5, 6); + +expect(10).to.not.be.above(20); +expect([1, 2, 3]).to.shallow.include(3); +expect([1, 1, 2]).to.only.include([1, 2]); +expect([1, 2]).to.once.include([1, 2]); +expect([1, 2, 3]).to.part.include([1, 4]); + +expect(10, "Age").to.be.above(5); + +const func = function () { return arguments; }; +expect(func()).to.be.arguments(); + +expect([1, 2]).to.be.an.array(); + +expect(true).to.be.a.boolean(); + +expect(new Date()).to.be.a.date(); + +const err = new Error("Oops an error occured."); +expect(err).to.be.an.error(); +expect(err).to.be.an.error(Error); +expect(err).to.be.an.error("Oops an error occured."); +expect(err).to.be.an.error(Error, /occured/); + +expect(function () { }).to.be.a.function(); + +expect(123).to.be.a.number(); + +expect(/abc/).to.be.a.regexp(); + +expect("abc").to.be.a.string(); + +expect({ a: "1" }).to.be.an.object(); + +expect(true).to.be.true(); + +expect(false).to.be.false(); + +expect(null).to.be.null(); + +expect(undefined).to.be.undefined(); + +expect("abc").to.include("ab"); +expect("abc").to.only.include("abc"); +expect("aaa").to.only.include("a"); +expect("abc").to.once.include("b"); +expect("abc").to.include(["a", "c"]); +expect("abc").to.part.include(["a", "d"]); + +expect([1, 2, 3]).to.include(1); +expect([{ a: 1 }]).to.include({ a: 1 }); +expect([1, 2, 3]).to.include([1, 2]); +expect([{ a: 1 }]).to.include([{ a: 1 }]); +expect([1, 1, 2]).to.only.include([1, 2]); +expect([1, 2]).to.once.include([1, 2]); +expect([1, 2, 3]).to.part.include([1, 4]); +expect([[1], [2]]).to.include([[1]]); + +interface TestType { + a: number; + b?: number; + c?: number; + d?: number; +} + +interface TestType2 { + a: number[]; + b?: number[]; + c: number[]; +} + +expect({ a: 1, b: 2, c: 3 }).to.include("a"); +expect({ a: 1, b: 2, c: 3 }).to.include(["a", "c"]); +expect({ a: 1, b: 2, c: 3 }).to.only.include(["a", "b", "c"]); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1 }); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1 }); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1, c: 3 }); +expect({ a: 1, b: 2, c: 3 }).to.part.include({ a: 1, d: 4 }); +expect({ a: 1, b: 2, c: 3 }).to.part.include({ a: 1, d: 4 }); +expect({ a: 1, b: 2, c: 3 }).to.only.include({ a: 1, b: 2, c: 3 }); +expect({ a: [1], b: [2], c: [3] }).to.include({ a: [1], c: [3] }); +expect({ a: [1], b: [2], c: [3] }).to.include({ a: [1], c: [3] }); + +expect("https://example.org/secure").to.startWith("https://"); + +expect("http://example.org/relative").to.endWith("/relative"); + +expect(4).to.exist(); +expect(null).to.not.exist(); + +expect("abc").to.be.empty(); + +expect("abcd").to.have.length(4); + +expect(5).to.equal(5); +expect({ a: 1 }).to.equal({ a: 1 }); + +expect(Object.create(null)).to.equal({}, { prototype: false }); + +expect(5).to.shallow.equal(5); +expect({ a: 1 }).to.shallow.equal({ a: 1 }); + +expect(10).to.be.above(5); + +expect(10).to.be.at.least(10); + +expect(10).to.be.below(20); + +expect(10).to.be.at.most(10); + +expect(10).to.be.within(10, 20); +expect(20).to.be.within(10, 20); + +expect(15).to.be.between(10, 20); + +expect(10).to.be.about(9, 1); + +expect(new Date()).to.be.an.instanceof(Date); + +expect("a5").to.match(/\w\d/); +expect(["abc", "def"]).to.match(/^[\w\d,]*$/); +expect(1).to.match(/^\d$/); + +expect("x").to.satisfy(value => value === "x"); + +class CustomError extends Error { + call: (message: string) => Error; +} + +const throws = function () { + + throw new CustomError("Oh no!"); +}; + +expect(throws).to.throw(CustomError, "Oh no!"); + +fail("This should not occur"); + +expect(count()).to.be.a.number(); + +expect(incomplete()).to.be.null().and.not.be.an.array(); + +const error = thrownAt(new Error("oops")); +expect(error).to.not.be.undefined(); +expect(error.column).to.exist(); + +const foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; +settings.truncateMessages = false; +expect(foo).to.equal([]); + +const bar = Object.create(null); +settings.comparePrototypes = false; +expect(bar).to.equal({}); diff --git a/code/index.d.ts b/code/index.d.ts new file mode 100644 index 0000000000..174215f5d8 --- /dev/null +++ b/code/index.d.ts @@ -0,0 +1,188 @@ +// Type definitions for code 4.0.0 +// Project: https://github.com/hapijs/code +// Definitions by: Prashant Tiwari +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Generates an assertion object. */ +export function expect(value: T | T[], prefix?: string): AssertionChain; +/** Makes the test fail with the given message. */ +export function fail(message: string): void; +/** Returns the total number of assertions created using the expect() method. */ +export function count(): number; +/** Returns an array of the locations where incomplete assertions were declared or null if no incomplete assertions found. */ +export function incomplete(): Array | null; +/** Returns the filename, line number, and column number of where the error was created. */ +export function thrownAt(error?: Error): CodeError; +/** Configure code. */ +export const settings: Settings; + +type AssertionChain = Assertion & Expectation; + +interface Assertion extends Grammar, Flags { } + +interface Expectation extends Types, Values { } + +interface Grammar { + /** Connecting word. */ + a: AssertionChain; + /** Connecting word. */ + an: AssertionChain; + /** Connecting word. */ + and: AssertionChain; + /** Connecting word. */ + at: AssertionChain; + /** Connecting word. */ + be: AssertionChain; + /** Connecting word. */ + have: AssertionChain; + /** Connecting word. */ + in: AssertionChain; + /** Connecting word. */ + to: AssertionChain; +} + +interface Flags { + /** Inverses the expected result of any assertion */ + not: AssertionChain; + /** + * Requires that inclusion matches appear only once in the provided value. + * Used by include(). + */ + once: AssertionChain; + /** + * Requires that only the provided elements appear in the provided value. + * Used by include(). + */ + only: AssertionChain; + /** + * Allows a partial match when asserting inclusion + * Used by include(). Defaults to false. + */ + part: AssertionChain; + /** + * Performs a comparison using strict equality (===). + * Code defaults to deep comparison. Used by equal() and include(). + */ + shallow: AssertionChain; +} + +interface Types { + /** Asserts that the reference value is an arguments object. */ + arguments(): AssertionChain; + /** Asserts that the reference value is an Array. */ + array(): AssertionChain; + /** Asserts that the reference value is a boolean. */ + boolean(): AssertionChain; + /** Asserts that the reference value is a Buffer. */ + buffer(): AssertionChain; + /** Asserts that the reference value is a Date. */ + date(): AssertionChain; + /** Asserts that the reference value is an error. */ + error(type?: Object, message?: string | RegExp): AssertionChain; + /** Asserts that the reference value is a function. */ + function(): AssertionChain; + /** Asserts that the reference value is a number. */ + number(): AssertionChain; + /** Asserts that the reference value is a RegExp. */ + regexp(): AssertionChain; + /** Asserts that the reference value is a string. */ + string(): AssertionChain; + /** Asserts that the reference value is an object (excluding array, buffer, or other native objects). */ + object(): AssertionChain; +} + +interface Values { + /** Asserts that the reference value is true. */ + true(): AssertionChain; + /** Asserts that the reference value is false. */ + false(): AssertionChain; + /** Asserts that the reference value is null. */ + null(): AssertionChain; + /** Asserts that the reference value is undefined. */ + undefined(): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + include(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + includes(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + contain(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + contains(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string) starts with the provided value. */ + startWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) starts with the provided value. */ + startsWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) ends with the provided value. */ + endWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) ends with the provided value. */ + endsWith(value: string): AssertionChain; + /** Asserts that the reference value exists (not null or undefined). */ + exist(): AssertionChain; + /** Asserts that the reference value exists (not null or undefined). */ + exists(): AssertionChain; + /** Asserts that the reference value has a length property equal to zero or an object with no keys. */ + empty(): AssertionChain; + /** Asserts that the reference value has a length property matching the provided size or an object with the specified number of keys. */ + length(size: number): AssertionChain; + /** Asserts that the reference value equals the provided value. */ + equal(value: T, options?: any): AssertionChain; + /** Asserts that the reference value equals the provided value. */ + equals(value: T, options?: any): AssertionChain; + /** Asserts that the reference value is greater than (>) the provided value. */ + above(value: T): AssertionChain; + /** Asserts that the reference value is greater than (>) the provided value. */ + greaterThan(value: T): AssertionChain; + /** Asserts that the reference value is at least (>=) the provided value. */ + least(value: T): AssertionChain; + /** Asserts that the reference value is at least (>=) the provided value. */ + min(value: T): AssertionChain; + /** Asserts that the reference value is less than (<) the provided value. */ + below(value: T): AssertionChain; + /** Asserts that the reference value is less than (<) the provided value. */ + lessThan(value: T): AssertionChain; + /** Asserts that the reference value is at most (<=) the provided value. */ + most(value: T): AssertionChain; + /** Asserts that the reference value is at most (<=) the provided value. */ + max(value: T): AssertionChain; + /** Asserts that the reference value is within (from <= value <= to) the provided values. */ + within(from: T, to: T): AssertionChain; + /** Asserts that the reference value is within (from <= value <= to) the provided values. */ + range(from: T, to: T): AssertionChain; + /** Asserts that the reference value is between but not equal (from < value < to) the provided values. */ + between(from: T, to: T): AssertionChain; + /** Asserts that the reference value is about the provided value within a delta margin of difference. */ + about(value: number, delta: number): AssertionChain; + /** Asserts that the reference value has the provided instanceof value. */ + instanceof(type: Object): AssertionChain; + /** Asserts that the reference value has the provided instanceof value. */ + instanceOf(type: Object): AssertionChain; + /** Asserts that the reference value's toString() representation matches the provided regular expression. */ + match(regex: RegExp): AssertionChain; + /** Asserts that the reference value's toString() representation matches the provided regular expression. */ + matches(regex: RegExp): AssertionChain; + /** Asserts that the reference value satisfies the provided validator function. */ + satisfy(validator: (value: T) => boolean): AssertionChain; + /** Asserts that the reference value satisfies the provided validator function. */ + satisfies(validator: (value: T) => boolean): AssertionChain; + /** Asserts that the function reference value throws an exception when called. */ + throw(type: Object, message: string | RegExp): AssertionChain; +} + +interface Settings { + /** + * Truncate long assertion error messages for readability? + * Defaults to true. + */ + truncateMessages?: boolean; + /** + * Ignore object prototypes when doing a deep comparison? + * Defaults to false. + */ + comparePrototypes?: boolean; +} + +interface CodeError { + filename: string; + line: string; + column: string; +} diff --git a/code/tsconfig.json b/code/tsconfig.json new file mode 100644 index 0000000000..d0299c6345 --- /dev/null +++ b/code/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "code-tests.ts" + ] +} \ No newline at end of file From 34f6ecfb32443b43cb0c4194dbcf457d34eaffb4 Mon Sep 17 00:00:00 2001 From: "Scott(JuJiang)" Date: Wed, 2 Nov 2016 22:54:22 +0800 Subject: [PATCH 038/131] feat: add definition for memory-fs (#12377) * feat: add definition for memory-fs * fix: enable strictNullChecks and adjust tests * feat: add standalone module definitions for memory-fs --- memory-fs/index.d.ts | 83 ++++++++++++++++++++++++++++++++ memory-fs/lib/join-tests.ts | 3 ++ memory-fs/lib/join.d.ts | 3 ++ memory-fs/lib/normalize-tests.ts | 3 ++ memory-fs/lib/normalize.d.ts | 3 ++ memory-fs/memory-fs-tests.ts | 19 ++++++++ memory-fs/tsconfig.json | 23 +++++++++ 7 files changed, 137 insertions(+) create mode 100644 memory-fs/index.d.ts create mode 100644 memory-fs/lib/join-tests.ts create mode 100644 memory-fs/lib/join.d.ts create mode 100644 memory-fs/lib/normalize-tests.ts create mode 100644 memory-fs/lib/normalize.d.ts create mode 100644 memory-fs/memory-fs-tests.ts create mode 100644 memory-fs/tsconfig.json diff --git a/memory-fs/index.d.ts b/memory-fs/index.d.ts new file mode 100644 index 0000000000..9578bb3548 --- /dev/null +++ b/memory-fs/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for memory-fs 0.3.0 +// Project: https://github.com/webpack/memory-fs +// Definitions by: e-cloud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare class MemoryFileSystem { + data: any; + + constructor(data?: any); + + meta(_path: string): any; + + existsSync(_path: string): boolean; + + statSync(_path: string): { + isFile: () => boolean; + isDirectory: () => boolean; + isBlockDevice: () => boolean; + isCharacterDevice: () => boolean; + isSymbolicLink: () => boolean; + isFIFO: () => boolean; + isSocket: () => boolean; + }; + + readFileSync(_path: string, encoding?: string): any; + + readdirSync(_path: string): string[]; + + mkdirpSync(_path: string): void; + + mkdirSync(_path: string): void; + + _remove(_path: string, name: string, testFn: ((part: string) => boolean)): void; + + rmdirSync(_path: string): void; + + unlinkSync(_path: string): void; + + readlinkSync(_path: string): void; + + writeFileSync(_path: string, content: string | Buffer, encoding?: string): void; + + createReadStream( + path: string, options: { + start: number; + end: number; + } + ): any; + + createWriteStream(path: string, options: any): any; + + exists(path: string, callback: (isExist: boolean) => any): any; + + writeFile(path: string, content: string | Buffer, callback: (err?: Error) => any): any; + + writeFile(path: string, content: string | Buffer, encoding: string, callback: (err?: Error) => any): any; + + join(path: string, request: string): string; + + pathToArray(path: string): string[]; + + normalize(path: string): string; + + stat(path: string, callback: (err?: Error, result?: any) => any): void; + + readdir(path: string, callback: (err?: Error, result?: any) => any): void; + + mkdirp(path: string, callback: (err?: Error, result?: any) => any): void; + + rmdir(path: string, callback: (err?: Error, result?: any) => any): void; + + unlink(path: string, callback: (err?: Error, result?: any) => any): void; + + readlink(path: string, callback: (err?: Error, result?: any) => any): void; + + mkdir(path: string, optArg: {}, callback: (err?: Error, result?: any) => any): void; + + readFile(path: string, optArg: {}, callback: (err?: Error, result?: any) => any): void; +} + +export = MemoryFileSystem; diff --git a/memory-fs/lib/join-tests.ts b/memory-fs/lib/join-tests.ts new file mode 100644 index 0000000000..0394cab49f --- /dev/null +++ b/memory-fs/lib/join-tests.ts @@ -0,0 +1,3 @@ +import memoryFsJoin = require('memory-fs/lib/join'); + +memoryFsJoin('hello', 'world'); diff --git a/memory-fs/lib/join.d.ts b/memory-fs/lib/join.d.ts new file mode 100644 index 0000000000..bf15ba3185 --- /dev/null +++ b/memory-fs/lib/join.d.ts @@ -0,0 +1,3 @@ +declare function join(path: string, request: string): string; + +export = join; diff --git a/memory-fs/lib/normalize-tests.ts b/memory-fs/lib/normalize-tests.ts new file mode 100644 index 0000000000..b92c43f717 --- /dev/null +++ b/memory-fs/lib/normalize-tests.ts @@ -0,0 +1,3 @@ +import normalize = require('memory-fs/lib/normalize'); + +normalize('hello world'); diff --git a/memory-fs/lib/normalize.d.ts b/memory-fs/lib/normalize.d.ts new file mode 100644 index 0000000000..807609661d --- /dev/null +++ b/memory-fs/lib/normalize.d.ts @@ -0,0 +1,3 @@ +declare function normalize(path: string): string; + +export = normalize; diff --git a/memory-fs/memory-fs-tests.ts b/memory-fs/memory-fs-tests.ts new file mode 100644 index 0000000000..61302916be --- /dev/null +++ b/memory-fs/memory-fs-tests.ts @@ -0,0 +1,19 @@ +/// + +import MemoryFileSystem = require('memory-fs'); + +const fs = new MemoryFileSystem({}); + +fs.existsSync('./kd/sdkfj'); + +fs.writeFile('hello', 'hahahahah', function (err) { + if(err){ + console.log(err.message); + } +}); + +fs.writeFile('hello', 'hahahahah', 'utf-8', function (err) { + if(err){ + console.log(err.message); + } +}); diff --git a/memory-fs/tsconfig.json b/memory-fs/tsconfig.json new file mode 100644 index 0000000000..105762a5a1 --- /dev/null +++ b/memory-fs/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "memory-fs-tests.ts", + "lib/join-tests.ts", + "lib/join.d.ts", + "lib/normalize-tests.ts", + "lib/normalize.d.ts" + ] +} From 5b3fcc4f7d0e404b738f86195f8f49035b6133c5 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Tue, 1 Nov 2016 15:25:15 +0200 Subject: [PATCH 039/131] [material-ui] Add boolean for muiTheme.userAgent It turns out that `muiTheme.userAgent` supports booleans as well. This is used when you want to disable the autoprefixer functionality: https://github.com/callemall/material-ui/blob/ccf712c5733508784cd709c18c29059542d6aad1/src/utils/autoprefixer.js#L20 --- material-ui/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 941b7aff72..c04d673dc9 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -141,7 +141,7 @@ declare namespace __MaterialUI { fontFamily?: string; palette?: ThemePalette; isRtl?: boolean; - userAgent?: string; + userAgent?: string | boolean; zIndex?: zIndex; baseTheme?: RawTheme; rawTheme?: RawTheme; From 30907212e76218a3b7b9ee03a149addaa55f5820 Mon Sep 17 00:00:00 2001 From: Miroshin Stepan Date: Wed, 2 Nov 2016 18:13:19 +0300 Subject: [PATCH 040/131] Update pkcs11js (#12442) * Add files * Added all types from pkijs-es6 * Update - Added pkijs test - Created asn1js - Created pvutils - Fixed type errors * Update asn1js typings * Update pvutils test * Remove PKIBase * Added common modules x509, cms, ocsp * Fix typings errors * Add comments * Update 'declare module' & config * Fix type errors --- pkcs11js/index.d.ts | 2336 ++++++++++++++++++++-------------------- pkcs11js/tsconfig.json | 2 +- 2 files changed, 1172 insertions(+), 1166 deletions(-) diff --git a/pkcs11js/index.d.ts b/pkcs11js/index.d.ts index ab5a38e30b..cbd4ef3670 100644 --- a/pkcs11js/index.d.ts +++ b/pkcs11js/index.d.ts @@ -10,1214 +10,1220 @@ * v1.0.3 */ -type Handle = Buffer; +export = Pkcs11js; + +declare namespace Pkcs11js { + + type Handle = Buffer; -interface Version { - major: number; - minor: number; -} + interface Version { + major: number; + minor: number; + } -interface ModuleInfo { - cryptokiVersion: Version; - manufacturerID: string; - flags: number; - libraryDescription: string; - libraryVersion: Version; -} + interface ModuleInfo { + cryptokiVersion: Version; + manufacturerID: string; + flags: number; + libraryDescription: string; + libraryVersion: Version; + } -interface SlotInfo { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: Version; - firmwareVersion: Version -} + interface SlotInfo { + slotDescription: string; + manufacturerID: string; + flags: number; + hardwareVersion: Version; + firmwareVersion: Version + } -interface TokenInfo { - label: string; - manufacturerID: string; - model: string; - serialNumber: string; - flags: number; - maxSessionCount: number; - sessionCount: number; - maxRwSessionCount: number; - rwSessionCount: number; - maxPinLen: number; - minPinLen: number; - hardwareVersion: Version; - firmwareVersion: Version; - utcTime: string - totalPublicMemory: number; - freePublicMemory: number; - totalPrivateMemory: number; - freePrivateMemory: number; -} + interface TokenInfo { + label: string; + manufacturerID: string; + model: string; + serialNumber: string; + flags: number; + maxSessionCount: number; + sessionCount: number; + maxRwSessionCount: number; + rwSessionCount: number; + maxPinLen: number; + minPinLen: number; + hardwareVersion: Version; + firmwareVersion: Version; + utcTime: string + totalPublicMemory: number; + freePublicMemory: number; + totalPrivateMemory: number; + freePrivateMemory: number; + } -interface MechanismInfo { - minKeySize: number; - maxKeySize: number; - flags: number; -} + interface MechanismInfo { + minKeySize: number; + maxKeySize: number; + flags: number; + } -interface SessionInfo { - slotID: number; - state: number; - flags: number; - deviceError: number; -} + interface SessionInfo { + slotID: number; + state: number; + flags: number; + deviceError: number; + } -type Template = Attribute[]; + type Template = Attribute[]; -interface Attribute { - type: number; - value?: number | boolean | string | Buffer; -} + interface Attribute { + type: number; + value?: number | boolean | string | Buffer; + } -interface Mechanism { - mechanism: number; - parameter: Buffer | IParapms; -} + interface Mechanism { + mechanism: number; + parameter: Buffer | IParapms; + } -// Crpto parameters + // Crpto parameters -interface IParapms { - /** - * Type of crypto param. Uses consts CK_PARAMS_* - * - * @type {number} - */ - type: number; -} + interface IParapms { + /** + * Type of crypto param. Uses consts CK_PARAMS_* + * + * @type {number} + */ + type: number; + } -interface ECDH1 extends IParapms { - kdf: number; - sharedData?: Buffer; - publicData: Buffer; -} + interface ECDH1 extends IParapms { + kdf: number; + sharedData?: Buffer; + publicData: Buffer; + } -interface AesCBC extends IParapms { - iv: Buffer; - data?: Buffer; -} + interface AesCBC extends IParapms { + iv: Buffer; + data?: Buffer; + } -interface AesCCM extends IParapms { - dataLen: number; - nonce?: Buffer; - aad?: Buffer; - macLen: number; -} + interface AesCCM extends IParapms { + dataLen: number; + nonce?: Buffer; + aad?: Buffer; + macLen: number; + } -interface AesGCM extends IParapms { - iv?: Buffer; - aad?: Buffer; - ivBits: number; - tagBits: number; -} + interface AesGCM extends IParapms { + iv?: Buffer; + aad?: Buffer; + ivBits: number; + tagBits: number; + } -interface RsaOAEP extends IParapms { - hashAlg: number; - mgf: number; - source: number; - sourceData?: Buffer; -} + interface RsaOAEP extends IParapms { + hashAlg: number; + mgf: number; + source: number; + sourceData?: Buffer; + } -interface RsaPSS extends IParapms { - hashAlg: number; - mgf: number; - saltLen: number; -} + interface RsaPSS extends IParapms { + hashAlg: number; + mgf: number; + saltLen: number; + } -interface KeyPair { - privateKey: Handle, - publicKey: Handle, -} + interface KeyPair { + privateKey: Handle, + publicKey: Handle, + } -export class PKCS11 { - /** - * Loads dynamic library with PKCS#11 interface - * - * @param {string} path - */ - load(path: string): void; - /** - * Initializes the Cryptoki library - */ - C_Initialize(): void; - /** - * Indicates that an application is done with the Cryptoki library - */ - C_Finalize(): void; - /** - * Returns general information about Cryptoki - * - * @returns {ModuleInfo} - */ - C_GetInfo(): ModuleInfo; + export class PKCS11 { + /** + * Loads dynamic library with PKCS#11 interface + * + * @param {string} path + */ + load(path: string): void; + /** + * Initializes the Cryptoki library + */ + C_Initialize(): void; + /** + * Indicates that an application is done with the Cryptoki library + */ + C_Finalize(): void; + /** + * Returns general information about Cryptoki + * + * @returns {ModuleInfo} + */ + C_GetInfo(): ModuleInfo; - /* Slot and token management */ + /* Slot and token management */ - /** - * obtains a list of slots in the system - * - * @param {boolean} [tokenPresent] Only slots with tokens? - * @returns {Handle[]} Array of slot IDs - */ - C_GetSlotList(tokenPresent?: boolean): Handle[]; - /** - * Obtains information about a particular slot in the system - * - * @param {Handle} slot The ID of the slot - * @returns {SlotInfo} Receives the slot information - */ - C_GetSlotInfo(slot: Handle): SlotInfo; - /** - * Obtains information about a particular token in the system - * - * @param {Handle} slot ID of the token's slot - * @returns {TokenInfo} Receives the token information - */ - C_GetTokenInfo(slot: Handle): TokenInfo; - /** - * Initializes a token - * - * @param {Handle} slot ID of the token's slot - * @param {string} [pin] The SO's initial PIN - * @returns {string} 32-byte token label (blank padded) - */ - C_InitToken(slot: Handle, pin?: string): string; - /** - * Initializes the normal user's PIN - * - * @param {Handle} session The session's handle - * @param {string} [pin] The normal user's PIN - */ - C_InitPIN(session: Handle, pin?: string): void; - /** - * Modifies the PIN of the user who is logged in - * - * @param {Handle} session The session's handle - * @param {string} oldPin The old PIN - * @param {string} newPin The new PIN - */ - C_SetPIN(session: Handle, oldPin: string, newPin: string): void; - /** - * Obtains a list of mechanism types supported by a token - * - * @param {Handle} slot ID of token's slot - * @returns {Handle[]} Gets mech. array - */ - C_GetMechanismList(slot: Handle): Handle[]; - /** - * Obtains information about a particular mechanism possibly supported by a token - * - * @param {Handle} slot ID of the token's slot - * @param {Handle} mech Type of mechanism - * @returns {MechanismInfo} Receives mechanism info - */ - C_GetMechanismInfo(slot: Handle, mech: Handle): MechanismInfo; + /** + * obtains a list of slots in the system + * + * @param {boolean} [tokenPresent] Only slots with tokens? + * @returns {Handle[]} Array of slot IDs + */ + C_GetSlotList(tokenPresent?: boolean): Handle[]; + /** + * Obtains information about a particular slot in the system + * + * @param {Handle} slot The ID of the slot + * @returns {SlotInfo} Receives the slot information + */ + C_GetSlotInfo(slot: Handle): SlotInfo; + /** + * Obtains information about a particular token in the system + * + * @param {Handle} slot ID of the token's slot + * @returns {TokenInfo} Receives the token information + */ + C_GetTokenInfo(slot: Handle): TokenInfo; + /** + * Initializes a token + * + * @param {Handle} slot ID of the token's slot + * @param {string} [pin] The SO's initial PIN + * @returns {string} 32-byte token label (blank padded) + */ + C_InitToken(slot: Handle, pin?: string): string; + /** + * Initializes the normal user's PIN + * + * @param {Handle} session The session's handle + * @param {string} [pin] The normal user's PIN + */ + C_InitPIN(session: Handle, pin?: string): void; + /** + * Modifies the PIN of the user who is logged in + * + * @param {Handle} session The session's handle + * @param {string} oldPin The old PIN + * @param {string} newPin The new PIN + */ + C_SetPIN(session: Handle, oldPin: string, newPin: string): void; + /** + * Obtains a list of mechanism types supported by a token + * + * @param {Handle} slot ID of token's slot + * @returns {number[]} Gets mech. array + */ + C_GetMechanismList(slot: Handle): number[]; + /** + * Obtains information about a particular mechanism possibly supported by a token + * + * @param {Handle} slot ID of the token's slot + * @param {number} mech Type of mechanism + * @returns {MechanismInfo} Receives mechanism info + */ + C_GetMechanismInfo(slot: Handle, mech: number): MechanismInfo; - /* Session management */ + /* Session management */ - /** - * Opens a session between an application and a token - * - * @param {Handle} slot The slot's ID - * @param {number} flags From CK_SESSION_INFO - * @returns {Handle} Gets session handle - */ - C_OpenSession(slot: Handle, flags: number): Handle; - /** - * Closes a session between an application and a token - * - * @param {Handle} session The session's handle - */ - C_CloseSession(session: Handle): void; - /** - * Сloses all sessions with a token - * - * @param {Handle} slot The token's slot - */ - C_CloseAllSessions(slot: Handle): void; - /** - * Obtains information about the session - * - * @param {Handle} session The session's handle - * @returns {SessionInfo} Receives session info - */ - C_GetSessionInfo(session: Handle): SessionInfo; - /** - * Logs a user into a token - * - * @param {Handle} session The session's handle - * @param {number} userType The user type - * @param {string} [pin] The user's PIN - */ - C_Login(session: Handle, userType: number, pin?: string): void; - /** - * Logs a user out from a token - * - * @param {Handle} session The session's handle - */ - C_Logout(session: Handle): void; + /** + * Opens a session between an application and a token + * + * @param {Handle} slot The slot's ID + * @param {number} flags From CK_SESSION_INFO + * @returns {Handle} Gets session handle + */ + C_OpenSession(slot: Handle, flags: number): Handle; + /** + * Closes a session between an application and a token + * + * @param {Handle} session The session's handle + */ + C_CloseSession(session: Handle): void; + /** + * Сloses all sessions with a token + * + * @param {Handle} slot The token's slot + */ + C_CloseAllSessions(slot: Handle): void; + /** + * Obtains information about the session + * + * @param {Handle} session The session's handle + * @returns {SessionInfo} Receives session info + */ + C_GetSessionInfo(session: Handle): SessionInfo; + /** + * Logs a user into a token + * + * @param {Handle} session The session's handle + * @param {number} userType The user type + * @param {string} [pin] The user's PIN + */ + C_Login(session: Handle, userType: number, pin?: string): void; + /** + * Logs a user out from a token + * + * @param {Handle} session The session's handle + */ + C_Logout(session: Handle): void; - /* Object management */ + /* Object management */ - /** - * Creates a new object - * - * @param {Handle} session The session's handle - * @param {Template} template The object's template - * @returns {Handle} Gets new object's handle - */ - C_CreateObject(session: Handle, template: Template): Handle; - /** - * Copies an object, creating a new object for the copy - * - * @param {Handle} session The session's handle - * @param {Handle} object The object's handle - * @param {Template} template Template for new object - * @returns {Handle} Receives handle of copy - */ - C_CopyObject(session: Handle, object: Handle, template: Template): Handle; - /** - * Destroys an object - * - * @param {Handle} session The session's handle - * @param {Handle} object The object's handle - */ - C_DestroyObject(session: Handle, object: Handle): void; - /** - * Gets the size of an object in bytes - * - * @param {Handle} session The session's handle - * @param {Handle} object The object's handle - * @returns {number} Receives size of object - */ - C_GetObjectSize(session: Handle, object: Handle): number; - /** - * Initializes a search for token and session objects that match a template - * - * @param {Handle} session The session's handle - * @param {Template} template Attribute values to match - */ - C_FindObjectsInit(session: Handle, template: Template): void; - /** - * Continues a search for token and session - * objects that match a template, obtaining additional object - * handles - * - * @param {Handle} session Session's handle - * @returns {Handle} gets Object's handle. If Object is not found - * the result is 0 - */ - C_FindObjects(session: Handle): Handle; - /** - * Finishes a search for token and session objects - * - * @param {Handle} session The session's handle - */ - C_FindObjectsFinal(session: Handle): void; - /** - * Obtains the value of one or more object attributes - * - * @param {Handle} session The session's handle - * @param {Handle} object The object's handle - * @param {Template} template Specifies attrs; gets vals - * @returns {Template} Receives attributes with values - */ - C_GetAttributeValue(session: Handle, object: Handle, template: Template): Template; - /** - * Modifies the value of one or more object attributes - * - * @param {Handle} session The session's handle - * @param {Handle} object The object's handle - * @param {Template} template Specifies attrs and values - */ - C_SetAttributeValue(session: Handle, object: Handle, template: Template): void; + /** + * Creates a new object + * + * @param {Handle} session The session's handle + * @param {Template} template The object's template + * @returns {Handle} Gets new object's handle + */ + C_CreateObject(session: Handle, template: Template): Handle; + /** + * Copies an object, creating a new object for the copy + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Template for new object + * @returns {Handle} Receives handle of copy + */ + C_CopyObject(session: Handle, object: Handle, template: Template): Handle; + /** + * Destroys an object + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + */ + C_DestroyObject(session: Handle, object: Handle): void; + /** + * Gets the size of an object in bytes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @returns {number} Receives size of object + */ + C_GetObjectSize(session: Handle, object: Handle): number; + /** + * Initializes a search for token and session objects that match a template + * + * @param {Handle} session The session's handle + * @param {Template} template Attribute values to match + */ + C_FindObjectsInit(session: Handle, template: Template): void; + /** + * Continues a search for token and session + * objects that match a template, obtaining additional object + * handles + * + * @param {Handle} session Session's handle + * @returns {Handle} gets Object's handle. If Object is not found + * the result is 0 + */ + C_FindObjects(session: Handle): Handle; + /** + * Finishes a search for token and session objects + * + * @param {Handle} session The session's handle + */ + C_FindObjectsFinal(session: Handle): void; + /** + * Obtains the value of one or more object attributes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Specifies attrs; gets vals + * @returns {Template} Receives attributes with values + */ + C_GetAttributeValue(session: Handle, object: Handle, template: Template): Template; + /** + * Modifies the value of one or more object attributes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Specifies attrs and values + */ + C_SetAttributeValue(session: Handle, object: Handle, template: Template): void; - /* Encryption and decryption */ + /* Encryption and decryption */ - /** - * Initializes an encryption operation - * - * @param {Handle} session The session's handle - * @param {Mechanism} mechanism The encryption mechanism - * @param {Handle} key Handle of encryption key - */ - C_EncryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; - /** - * Encrypts single-part data - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Comming data - * @returns {Buffer} - */ - C_Encrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Encrypts single-part data - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Comming data - * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced comming data - */ - C_Encrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; - /** - * Continues a multiple-part encryption operation - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_EncryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Finishes a multiple-part encryption operation - * - * @param {Handle} session Session's handle - * @param {Buffer} outData Last coming data - * @returns {Buffer} Sliced coming data - */ - C_EncryptFinal(session: Handle, outData: Buffer): Buffer; - /** - * Initializes a decryption operation - * - * @param {Handle} session The session's handle - * @param {Mechanism} mechanism The decryption mechanism - * @param {Handle} key Handle of decryption key - */ - C_DecryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; - /** - * Decrypts encrypted data in a single part - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_Decrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Decrypts encrypted data in a single part - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data - */ - C_Decrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; - /** - * continues a multiple-part decryption operation - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_DecryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Finishes a multiple-part decryption operation - * - * @param {Handle} session Session's handle - * @param {Buffer} outData Last part of coming data - * @returns {Buffer} Coming data - */ - C_DecryptFinal(session: Handle, outData: Buffer): Buffer; + /** + * Initializes an encryption operation + * + * @param {Handle} session The session's handle + * @param {Mechanism} mechanism The encryption mechanism + * @param {Handle} key Handle of encryption key + */ + C_EncryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Encrypts single-part data + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Comming data + * @returns {Buffer} + */ + C_Encrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Encrypts single-part data + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Comming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced comming data + */ + C_Encrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * Continues a multiple-part encryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_EncryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Finishes a multiple-part encryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Last coming data + * @returns {Buffer} Sliced coming data + */ + C_EncryptFinal(session: Handle, outData: Buffer): Buffer; + /** + * Initializes a decryption operation + * + * @param {Handle} session The session's handle + * @param {Mechanism} mechanism The decryption mechanism + * @param {Handle} key Handle of decryption key + */ + C_DecryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Decrypts encrypted data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Decrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Decrypts encrypted data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + */ + C_Decrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part decryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_DecryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Finishes a multiple-part decryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Last part of coming data + * @returns {Buffer} Coming data + */ + C_DecryptFinal(session: Handle, outData: Buffer): Buffer; - /* Message digesting */ + /* Message digesting */ - /** - * Initializes a message-digesting operation - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Digesting mechanism - */ - C_DigestInit(session: Handle, mechanism: Mechanism): void; - /** - * Digests data in a single part - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_Digest(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Digests data in a single part - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data - - */ - C_Digest(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; - /** - * continues a multiple-part message-digesting operation - * operation, by digesting the value of a secret key as part of - * the data already digested - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - */ - C_DigestUpdate(session: Handle, inData: Buffer): void; - /** - * Finishes a multiple-part message-digesting operation - * - * @param {Handle} session Session's handle - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_DigestFinal(session: Handle, outData: Buffer): Buffer; - // C_DigestKey(); + /** + * Initializes a message-digesting operation + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Digesting mechanism + */ + C_DigestInit(session: Handle, mechanism: Mechanism): void; + /** + * Digests data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Digest(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Digests data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + + */ + C_Digest(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part message-digesting operation + * operation, by digesting the value of a secret key as part of + * the data already digested + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_DigestUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part message-digesting operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_DigestFinal(session: Handle, outData: Buffer): Buffer; + // C_DigestKey(); - /* Signing and MACing */ + /* Signing and MACing */ - /** - * initializes a signature (private key encryption) - * operation, where the signature is (will be) an appendix to - * the data, and plaintext cannot be recovered from the - *signature - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Signature mechanism - * @param {Handle} key Handle of signature key - */ - C_SignInit(session: Handle, mechanism: Mechanism, key: Handle): void; - /** - * Signs (encrypts with private key) data in a single - * part, where the signature is (will be) an appendix to the - * data, and plaintext cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_Sign(session: Handle, inData: Buffer, outData: Buffer): Buffer; - /** - * Signs (encrypts with private key) data in a single - * part, where the signature is (will be) an appendix to the - * data, and plaintext cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} outData Coming data - * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data - */ - C_Sign(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; - /** - * continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - */ - C_SignUpdate(session: Handle, inData: Buffer): void; - /** - * Finishes a multiple-part signature operation, - * returning the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} outData Coming data - * @returns {Buffer} Sliced coming data - */ - C_SignFinal(session: Handle, outData: Buffer): Buffer; - // C_SignRecoverInit(); - // C_SignRecover(); + /** + * initializes a signature (private key encryption) + * operation, where the signature is (will be) an appendix to + * the data, and plaintext cannot be recovered from the + *signature + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Signature mechanism + * @param {Handle} key Handle of signature key + */ + C_SignInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Signs (encrypts with private key) data in a single + * part, where the signature is (will be) an appendix to the + * data, and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Sign(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Signs (encrypts with private key) data in a single + * part, where the signature is (will be) an appendix to the + * data, and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + */ + C_Sign(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part signature operation, + * where the signature is (will be) an appendix to the data, + * and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_SignUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part signature operation, + * returning the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_SignFinal(session: Handle, outData: Buffer): Buffer; + // C_SignRecoverInit(); + // C_SignRecover(); - /* Verifying signatures and MACs */ + /* Verifying signatures and MACs */ - /** - * initializes a verification operation, where the - * signature is an appendix to the data, and plaintext cannot - * cannot be recovered from the signature (e.g. DSA) - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Verification mechanism - * @param {Handle} key Verification key - */ - C_VerifyInit(session: Handle, mechanism: Mechanism, key: Handle): void; - /** - * Verifies a signature in a single-part operation, - * where the signature is an appendix to the data, and plaintext - * cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} signature Signature to verify - * @returns {boolean} Verification result - */ - C_Verify(session: Handle, inData: Buffer, signature: Buffer): boolean; - /** - * Verifies a signature in a single-part operation, - * where the signature is an appendix to the data, and plaintext - * cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - * @param {Buffer} signature Signature to verify - * @param {(error: Error, verify: boolean) => void} cb Async callback with verification result - */ - C_Verify(session: Handle, inData: Buffer, signature: Buffer, cb: (error: Error, verify: boolean) => void): void; - /** - * Continues a multiple-part verification - * operation, where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} inData Incoming data - */ - C_VerifyUpdate(session: Handle, inData: Buffer): void; - /** - * Finishes a multiple-part verification - * operation, checking the signature - * - * @param {Handle} session Session's handle - * @param {Buffer} signature Signature to verify - * @returns {boolean} - */ - C_VerifyFinal(session: Handle, signature: Buffer): boolean; - // C_VerifyRecoverInit(); - // C_VerifyRecover(); + /** + * initializes a verification operation, where the + * signature is an appendix to the data, and plaintext cannot + * cannot be recovered from the signature (e.g. DSA) + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Verification mechanism + * @param {Handle} key Verification key + */ + C_VerifyInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Verifies a signature in a single-part operation, + * where the signature is an appendix to the data, and plaintext + * cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} signature Signature to verify + * @returns {boolean} Verification result + */ + C_Verify(session: Handle, inData: Buffer, signature: Buffer): boolean; + /** + * Verifies a signature in a single-part operation, + * where the signature is an appendix to the data, and plaintext + * cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} signature Signature to verify + * @param {(error: Error, verify: boolean) => void} cb Async callback with verification result + */ + C_Verify(session: Handle, inData: Buffer, signature: Buffer, cb: (error: Error, verify: boolean) => void): void; + /** + * Continues a multiple-part verification + * operation, where the signature is an appendix to the data, + * and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_VerifyUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part verification + * operation, checking the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} signature Signature to verify + * @returns {boolean} + */ + C_VerifyFinal(session: Handle, signature: Buffer): boolean; + // C_VerifyRecoverInit(); + // C_VerifyRecover(); - /* Key management */ + /* Key management */ - /** - * Generates a secret key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key generation mechanism - * @param {Template} template Template for new key - * @returns {Handle} Gets handle of new key - */ - C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template): Handle; - /** - * Generates a secret key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key generation mechanism - * @param {Template} template Template for new key - * @param {(error: Error, key: Handle) => void} cb Async callback with handle of ne key - */ - C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template, cb: (error: Error, key: Handle) => void): void; - /** - * Generates a public-key/private-key pair, - * creating new key objects - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key generation mechanism - * @param {Template} publicTmpl Template for public key - * @param {Template} privateTmpl Template for private key - * @returns {KeyPair} Get handles for private and public keys - */ - C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template): KeyPair; - /** - * Generates a public-key/private-key pair, - * creating new key objects - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key generation mechanism - * @param {Template} publicTmpl Template for public key - * @param {Template} privateTmpl Template for private key - * @param {(error: Error, keys: KeyPair) => void} cb Async callback with handles for private and public keys - */ - C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template, cb: (error: Error, keys: KeyPair) => void): void; - /** - * Wraps (i.e., encrypts) a key - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Wrapping mechanism - * @param {Handle} wrappingKey Wrapping key - * @param {Handle} key Key to be wrapped - * @param {Buffer} wrappedKey Init buffer for wrapped key - * @returns {Buffer} Sliced wrapped key - */ - C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer): Buffer; - /** - * Wraps (i.e., encrypts) a key - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Wrapping mechanism - * @param {Handle} wrappingKey Wrapping key - * @param {Handle} key Key to be wrapped - * @param {Buffer} wrappedKey Init buffer for wrapped key - * @param {(error: Error, wrappedKey: Buffer) => void} cb Async callback with sliced wrapped key - */ - C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer, cb: (error: Error, wrappedKey: Buffer) => void): void; - /** - * Unwraps (decrypts) a wrapped key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Unwrapping mechanism - * @param {Handle} unwrappingKey Unwrapping key - * @param {Buffer} wrappedKey Wrapped key - * @param {Template} template New key template - * @returns {Handle} Gets new handle - */ - C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template): Handle; - /** - * Unwraps (decrypts) a wrapped key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Unwrapping mechanism - * @param {Handle} unwrappingKey Unwrapping key - * @param {Buffer} wrappedKey Wrapped key - * @param {Template} template New key template - * @param {(error: Error, key: Handle) => void} cb Async callback with new key handle - */ - C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template, cb: (error: Error, key: Handle) => void): void; - /** - * Derives a key from a base key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key derivation mechanism - * @param {Handle} key Base key - * @param {Template} template new key template - * @returns {Handle} Get new key handle - */ - C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template): Handle; - /** - * Derives a key from a base key, creating a new key object - * - * @param {Handle} session Session's handle - * @param {Mechanism} mechanism Key derivation mechanism - * @param {Handle} key Base key - * @param {Template} template new key template - * @param {(error: Error, hKey: Handle) => void} cb Async callback woth new key handle - */ - C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template, cb: (error: Error, hKey: Handle) => void): void; - /** - * Mixes additional seed material into the token's random number generator - * - * @param {Handle} session Session's handle - * @param {Buffer} buf The seed material - * @returns {Buffer} Seeded data - */ - C_SeedRandom(session: Handle, buf: Buffer): Buffer; - /** - * Generates random data - * - * @param {Handle} session Session's handle - * @param {Buffer} buf Init buffer - * @returns {Buffer} Receives the random data - */ - C_GenerateRandom(session: Handle, buf: Buffer): Buffer; -} + /** + * Generates a secret key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} template Template for new key + * @returns {Handle} Gets handle of new key + */ + C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template): Handle; + /** + * Generates a secret key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} template Template for new key + * @param {(error: Error, key: Handle) => void} cb Async callback with handle of ne key + */ + C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template, cb: (error: Error, key: Handle) => void): void; + /** + * Generates a public-key/private-key pair, + * creating new key objects + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} publicTmpl Template for public key + * @param {Template} privateTmpl Template for private key + * @returns {KeyPair} Get handles for private and public keys + */ + C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template): KeyPair; + /** + * Generates a public-key/private-key pair, + * creating new key objects + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} publicTmpl Template for public key + * @param {Template} privateTmpl Template for private key + * @param {(error: Error, keys: KeyPair) => void} cb Async callback with handles for private and public keys + */ + C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template, cb: (error: Error, keys: KeyPair) => void): void; + /** + * Wraps (i.e., encrypts) a key + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Wrapping mechanism + * @param {Handle} wrappingKey Wrapping key + * @param {Handle} key Key to be wrapped + * @param {Buffer} wrappedKey Init buffer for wrapped key + * @returns {Buffer} Sliced wrapped key + */ + C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer): Buffer; + /** + * Wraps (i.e., encrypts) a key + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Wrapping mechanism + * @param {Handle} wrappingKey Wrapping key + * @param {Handle} key Key to be wrapped + * @param {Buffer} wrappedKey Init buffer for wrapped key + * @param {(error: Error, wrappedKey: Buffer) => void} cb Async callback with sliced wrapped key + */ + C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer, cb: (error: Error, wrappedKey: Buffer) => void): void; + /** + * Unwraps (decrypts) a wrapped key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Unwrapping mechanism + * @param {Handle} unwrappingKey Unwrapping key + * @param {Buffer} wrappedKey Wrapped key + * @param {Template} template New key template + * @returns {Handle} Gets new handle + */ + C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template): Handle; + /** + * Unwraps (decrypts) a wrapped key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Unwrapping mechanism + * @param {Handle} unwrappingKey Unwrapping key + * @param {Buffer} wrappedKey Wrapped key + * @param {Template} template New key template + * @param {(error: Error, key: Handle) => void} cb Async callback with new key handle + */ + C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template, cb: (error: Error, key: Handle) => void): void; + /** + * Derives a key from a base key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key derivation mechanism + * @param {Handle} key Base key + * @param {Template} template new key template + * @returns {Handle} Get new key handle + */ + C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template): Handle; + /** + * Derives a key from a base key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key derivation mechanism + * @param {Handle} key Base key + * @param {Template} template new key template + * @param {(error: Error, hKey: Handle) => void} cb Async callback woth new key handle + */ + C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template, cb: (error: Error, hKey: Handle) => void): void; + /** + * Mixes additional seed material into the token's random number generator + * + * @param {Handle} session Session's handle + * @param {Buffer} buf The seed material + * @returns {Buffer} Seeded data + */ + C_SeedRandom(session: Handle, buf: Buffer): Buffer; + /** + * Generates random data + * + * @param {Handle} session Session's handle + * @param {Buffer} buf Init buffer + * @returns {Buffer} Receives the random data + */ + C_GenerateRandom(session: Handle, buf: Buffer): Buffer; + } -// Attributes -declare const CKA_CLASS: number; -declare const CKA_TOKEN: number; -declare const CKA_PRIVATE: number; -declare const CKA_LABEL: number; -declare const CKA_APPLICATION: number; -declare const CKA_VALUE: number; -declare const CKA_OBJECT_ID: number; -declare const CKA_CERTIFICATE_TYPE: number; -declare const CKA_ISSUER: number; -declare const CKA_SERIAL_NUMBER: number; -declare const CKA_AC_ISSUER: number; -declare const CKA_OWNER: number; -declare const CKA_ATTR_TYPES: number; -declare const CKA_TRUSTED: number; -declare const CKA_CERTIFICATE_CATEGORY: number; -declare const CKA_JAVA_MIDP_SECURITY_DOMAIN: number; -declare const CKA_URL: number; -declare const CKA_HASH_OF_SUBJECT_PUBLIC_KEY: number; -declare const CKA_HASH_OF_ISSUER_PUBLIC_KEY: number; -declare const CKA_CHECK_VALUE: number; -declare const CKA_KEY_TYPE: number; -declare const CKA_SUBJECT: number; -declare const CKA_ID: number; -declare const CKA_SENSITIVE: number; -declare const CKA_ENCRYPT: number; -declare const CKA_DECRYPT: number; -declare const CKA_WRAP: number; -declare const CKA_UNWRAP: number; -declare const CKA_SIGN: number; -declare const CKA_SIGN_RECOVER: number; -declare const CKA_VERIFY: number; -declare const CKA_VERIFY_RECOVER: number; -declare const CKA_DERIVE: number; -declare const CKA_START_DATE: number; -declare const CKA_END_DATE: number; -declare const CKA_MODULUS: number; -declare const CKA_MODULUS_BITS: number; -declare const CKA_PUBLIC_EXPONENT: number; -declare const CKA_PRIVATE_EXPONENT: number; -declare const CKA_PRIME_1: number; -declare const CKA_PRIME_2: number; -declare const CKA_EXPONENT_1: number; -declare const CKA_EXPONENT_2: number; -declare const CKA_COEFFICIENT: number; -declare const CKA_PRIME: number; -declare const CKA_SUBPRIME: number; -declare const CKA_BASE: number; -declare const CKA_PRIME_BITS: number; -declare const CKA_SUBPRIME_BITS: number; -declare const CKA_SUB_PRIME_BITS: number; -declare const CKA_VALUE_BITS: number; -declare const CKA_VALUE_LEN: number; -declare const CKA_EXTRACTABLE: number; -declare const CKA_LOCAL: number; -declare const CKA_NEVER_EXTRACTABLE: number; -declare const CKA_ALWAYS_SENSITIVE: number; -declare const CKA_KEY_GEN_MECHANISM: number; -declare const CKA_MODIFIABLE: number; -declare const CKA_ECDSA_PARAMS: number; -declare const CKA_EC_PARAMS: number; -declare const CKA_EC_POINT: number; -declare const CKA_SECONDARY_AUTH: number; -declare const CKA_AUTH_PIN_FLAGS: number; -declare const CKA_ALWAYS_AUTHENTICATE: number; -declare const CKA_WRAP_WITH_TRUSTED: number; -declare const CKA_WRAP_TEMPLATE: number; -declare const CKA_UNWRAP_TEMPLATE: number; -declare const CKA_DERIVE_TEMPLATE: number; -declare const CKA_OTP_FORMAT: number; -declare const CKA_OTP_LENGTH: number; -declare const CKA_OTP_TIME_INTERVAL: number; -declare const CKA_OTP_USER_FRIENDLY_MODE: number; -declare const CKA_OTP_CHALLENGE_REQUIREMENT: number; -declare const CKA_OTP_TIME_REQUIREMENT: number; -declare const CKA_OTP_COUNTER_REQUIREMENT: number; -declare const CKA_OTP_PIN_REQUIREMENT: number; -declare const CKA_OTP_COUNTER: number; -declare const CKA_OTP_TIME: number; -declare const CKA_OTP_USER_IDENTIFIER: number; -declare const CKA_OTP_SERVICE_IDENTIFIER: number; -declare const CKA_OTP_SERVICE_LOGO: number; -declare const CKA_OTP_SERVICE_LOGO_TYPE: number; -declare const CKA_GOSTR3410_PARAMS: number; -declare const CKA_GOSTR3411_PARAMS: number; -declare const CKA_GOST28147_PARAMS: number; -declare const CKA_HW_FEATURE_TYPE: number; -declare const CKA_RESET_ON_INIT: number; -declare const CKA_HAS_RESET: number; -declare const CKA_PIXEL_X: number; -declare const CKA_PIXEL_Y: number; -declare const CKA_RESOLUTION: number; -declare const CKA_CHAR_ROWS: number; -declare const CKA_CHAR_COLUMNS: number; -declare const CKA_COLOR: number; -declare const CKA_BITS_PER_PIXEL: number; -declare const CKA_CHAR_SETS: number; -declare const CKA_ENCODING_METHODS: number; -declare const CKA_MIME_TYPES: number; -declare const CKA_MECHANISM_TYPE: number; -declare const CKA_REQUIRED_CMS_ATTRIBUTES: number; -declare const CKA_DEFAULT_CMS_ATTRIBUTES: number; -declare const CKA_SUPPORTED_CMS_ATTRIBUTES: number; -declare const CKA_ALLOWED_MECHANISMS: number; -declare const CKA_VENDOR_DEFINED: number; + // Attributes + const CKA_CLASS: number; + const CKA_TOKEN: number; + const CKA_PRIVATE: number; + const CKA_LABEL: number; + const CKA_APPLICATION: number; + const CKA_VALUE: number; + const CKA_OBJECT_ID: number; + const CKA_CERTIFICATE_TYPE: number; + const CKA_ISSUER: number; + const CKA_SERIAL_NUMBER: number; + const CKA_AC_ISSUER: number; + const CKA_OWNER: number; + const CKA_ATTR_TYPES: number; + const CKA_TRUSTED: number; + const CKA_CERTIFICATE_CATEGORY: number; + const CKA_JAVA_MIDP_SECURITY_DOMAIN: number; + const CKA_URL: number; + const CKA_HASH_OF_SUBJECT_PUBLIC_KEY: number; + const CKA_HASH_OF_ISSUER_PUBLIC_KEY: number; + const CKA_CHECK_VALUE: number; + const CKA_KEY_TYPE: number; + const CKA_SUBJECT: number; + const CKA_ID: number; + const CKA_SENSITIVE: number; + const CKA_ENCRYPT: number; + const CKA_DECRYPT: number; + const CKA_WRAP: number; + const CKA_UNWRAP: number; + const CKA_SIGN: number; + const CKA_SIGN_RECOVER: number; + const CKA_VERIFY: number; + const CKA_VERIFY_RECOVER: number; + const CKA_DERIVE: number; + const CKA_START_DATE: number; + const CKA_END_DATE: number; + const CKA_MODULUS: number; + const CKA_MODULUS_BITS: number; + const CKA_PUBLIC_EXPONENT: number; + const CKA_PRIVATE_EXPONENT: number; + const CKA_PRIME_1: number; + const CKA_PRIME_2: number; + const CKA_EXPONENT_1: number; + const CKA_EXPONENT_2: number; + const CKA_COEFFICIENT: number; + const CKA_PRIME: number; + const CKA_SUBPRIME: number; + const CKA_BASE: number; + const CKA_PRIME_BITS: number; + const CKA_SUBPRIME_BITS: number; + const CKA_SUB_PRIME_BITS: number; + const CKA_VALUE_BITS: number; + const CKA_VALUE_LEN: number; + const CKA_EXTRACTABLE: number; + const CKA_LOCAL: number; + const CKA_NEVER_EXTRACTABLE: number; + const CKA_ALWAYS_SENSITIVE: number; + const CKA_KEY_GEN_MECHANISM: number; + const CKA_MODIFIABLE: number; + const CKA_ECDSA_PARAMS: number; + const CKA_EC_PARAMS: number; + const CKA_EC_POINT: number; + const CKA_SECONDARY_AUTH: number; + const CKA_AUTH_PIN_FLAGS: number; + const CKA_ALWAYS_AUTHENTICATE: number; + const CKA_WRAP_WITH_TRUSTED: number; + const CKA_WRAP_TEMPLATE: number; + const CKA_UNWRAP_TEMPLATE: number; + const CKA_DERIVE_TEMPLATE: number; + const CKA_OTP_FORMAT: number; + const CKA_OTP_LENGTH: number; + const CKA_OTP_TIME_INTERVAL: number; + const CKA_OTP_USER_FRIENDLY_MODE: number; + const CKA_OTP_CHALLENGE_REQUIREMENT: number; + const CKA_OTP_TIME_REQUIREMENT: number; + const CKA_OTP_COUNTER_REQUIREMENT: number; + const CKA_OTP_PIN_REQUIREMENT: number; + const CKA_OTP_COUNTER: number; + const CKA_OTP_TIME: number; + const CKA_OTP_USER_IDENTIFIER: number; + const CKA_OTP_SERVICE_IDENTIFIER: number; + const CKA_OTP_SERVICE_LOGO: number; + const CKA_OTP_SERVICE_LOGO_TYPE: number; + const CKA_GOSTR3410_PARAMS: number; + const CKA_GOSTR3411_PARAMS: number; + const CKA_GOST28147_PARAMS: number; + const CKA_HW_FEATURE_TYPE: number; + const CKA_RESET_ON_INIT: number; + const CKA_HAS_RESET: number; + const CKA_PIXEL_X: number; + const CKA_PIXEL_Y: number; + const CKA_RESOLUTION: number; + const CKA_CHAR_ROWS: number; + const CKA_CHAR_COLUMNS: number; + const CKA_COLOR: number; + const CKA_BITS_PER_PIXEL: number; + const CKA_CHAR_SETS: number; + const CKA_ENCODING_METHODS: number; + const CKA_MIME_TYPES: number; + const CKA_MECHANISM_TYPE: number; + const CKA_REQUIRED_CMS_ATTRIBUTES: number; + const CKA_DEFAULT_CMS_ATTRIBUTES: number; + const CKA_SUPPORTED_CMS_ATTRIBUTES: number; + const CKA_ALLOWED_MECHANISMS: number; + const CKA_VENDOR_DEFINED: number; -// Objects -declare const CKO_DATA: number; -declare const CKO_CERTIFICATE: number; -declare const CKO_PUBLIC_KEY: number; -declare const CKO_PRIVATE_KEY: number; -declare const CKO_SECRET_KEY: number; -declare const CKO_HW_FEATURE: number; -declare const CKO_DOMAIN_PARAMETERS: number; -declare const CKO_MECHANISM: number; -declare const CKO_OTP_KEY: number; -declare const CKO_VENDOR_DEFINED: number; + // Objects + const CKO_DATA: number; + const CKO_CERTIFICATE: number; + const CKO_PUBLIC_KEY: number; + const CKO_PRIVATE_KEY: number; + const CKO_SECRET_KEY: number; + const CKO_HW_FEATURE: number; + const CKO_DOMAIN_PARAMETERS: number; + const CKO_MECHANISM: number; + const CKO_OTP_KEY: number; + const CKO_VENDOR_DEFINED: number; -// Key types -declare const CKK_RSA: number; -declare const CKK_DSA: number; -declare const CKK_DH: number; -declare const CKK_ECDSA: number; -declare const CKK_EC: number; -declare const CKK_X9_42_DH: number; -declare const CKK_KEA: number; -declare const CKK_GENERIC_SECRET: number; -declare const CKK_RC2: number; -declare const CKK_RC4: number; -declare const CKK_DES: number; -declare const CKK_DES2: number; -declare const CKK_DES3: number; -declare const CKK_CAST: number; -declare const CKK_CAST3: number; -declare const CKK_CAST5: number; -declare const CKK_CAST128: number; -declare const CKK_RC5: number; -declare const CKK_IDEA: number; -declare const CKK_SKIPJACK: number; -declare const CKK_BATON: number; -declare const CKK_JUNIPER: number; -declare const CKK_CDMF: number; -declare const CKK_AES: number; -declare const CKK_BLOWFISH: number; -declare const CKK_TWOFISH: number; -declare const CKK_SECURID: number; -declare const CKK_HOTP: number; -declare const CKK_ACTI: number; -declare const CKK_CAMELLIA: number; -declare const CKK_ARIA: number; -declare const CKK_MD5_HMAC: number; -declare const CKK_SHA_1_HMAC: number; -declare const CKK_RIPEMD128_HMAC: number; -declare const CKK_RIPEMD160_HMAC: number; -declare const CKK_SHA256_HMAC: number; -declare const CKK_SHA384_HMAC: number; -declare const CKK_SHA512_HMAC: number; -declare const CKK_SHA224_HMAC: number; -declare const CKK_SEED: number; -declare const CKK_GOSTR3410: number; -declare const CKK_GOSTR3411: number; -declare const CKK_GOST28147: number; -declare const CKK_VENDOR_DEFINED: number; + // Key types + const CKK_RSA: number; + const CKK_DSA: number; + const CKK_DH: number; + const CKK_ECDSA: number; + const CKK_EC: number; + const CKK_X9_42_DH: number; + const CKK_KEA: number; + const CKK_GENERIC_SECRET: number; + const CKK_RC2: number; + const CKK_RC4: number; + const CKK_DES: number; + const CKK_DES2: number; + const CKK_DES3: number; + const CKK_CAST: number; + const CKK_CAST3: number; + const CKK_CAST5: number; + const CKK_CAST128: number; + const CKK_RC5: number; + const CKK_IDEA: number; + const CKK_SKIPJACK: number; + const CKK_BATON: number; + const CKK_JUNIPER: number; + const CKK_CDMF: number; + const CKK_AES: number; + const CKK_BLOWFISH: number; + const CKK_TWOFISH: number; + const CKK_SECURID: number; + const CKK_HOTP: number; + const CKK_ACTI: number; + const CKK_CAMELLIA: number; + const CKK_ARIA: number; + const CKK_MD5_HMAC: number; + const CKK_SHA_1_HMAC: number; + const CKK_RIPEMD128_HMAC: number; + const CKK_RIPEMD160_HMAC: number; + const CKK_SHA256_HMAC: number; + const CKK_SHA384_HMAC: number; + const CKK_SHA512_HMAC: number; + const CKK_SHA224_HMAC: number; + const CKK_SEED: number; + const CKK_GOSTR3410: number; + const CKK_GOSTR3411: number; + const CKK_GOST28147: number; + const CKK_VENDOR_DEFINED: number; -// Mechanism -declare const CKM_RSA_PKCS_KEY_PAIR_GEN: number; -declare const CKM_RSA_PKCS: number; -declare const CKM_RSA_9796: number; -declare const CKM_RSA_X_509: number; -declare const CKM_MD2_RSA_PKCS: number; -declare const CKM_MD5_RSA_PKCS: number; -declare const CKM_SHA1_RSA_PKCS: number; -declare const CKM_RIPEMD128_RSA_PKCS: number; -declare const CKM_RIPEMD160_RSA_PKCS: number; -declare const CKM_RSA_PKCS_OAEP: number; -declare const CKM_RSA_X9_31_KEY_PAIR_GEN: number; -declare const CKM_RSA_X9_31: number; -declare const CKM_SHA1_RSA_X9_31: number; -declare const CKM_RSA_PKCS_PSS: number; -declare const CKM_SHA1_RSA_PKCS_PSS: number; -declare const CKM_DSA_KEY_PAIR_GEN: number; -declare const CKM_DSA: number; -declare const CKM_DSA_SHA1: number; -declare const CKM_DSA_SHA224: number; -declare const CKM_DSA_SHA256: number; -declare const CKM_DSA_SHA384: number; -declare const CKM_DSA_SHA512: number; -declare const CKM_DH_PKCS_KEY_PAIR_GEN: number; -declare const CKM_DH_PKCS_DERIVE: number; -declare const CKM_X9_42_DH_KEY_PAIR_GEN: number; -declare const CKM_X9_42_DH_DERIVE: number; -declare const CKM_X9_42_DH_HYBRID_DERIVE: number; -declare const CKM_X9_42_MQV_DERIVE: number; -declare const CKM_SHA256_RSA_PKCS: number; -declare const CKM_SHA384_RSA_PKCS: number; -declare const CKM_SHA512_RSA_PKCS: number; -declare const CKM_SHA256_RSA_PKCS_PSS: number; -declare const CKM_SHA384_RSA_PKCS_PSS: number; -declare const CKM_SHA512_RSA_PKCS_PSS: number; -declare const CKM_SHA224_RSA_PKCS: number; -declare const CKM_SHA224_RSA_PKCS_PSS: number; -declare const CKM_RC2_KEY_GEN: number; -declare const CKM_RC2_ECB: number; -declare const CKM_RC2_CBC: number; -declare const CKM_RC2_MAC: number; -declare const CKM_RC2_MAC_GENERAL: number; -declare const CKM_RC2_CBC_PAD: number; -declare const CKM_RC4_KEY_GEN: number; -declare const CKM_RC4: number; -declare const CKM_DES_KEY_GEN: number; -declare const CKM_DES_ECB: number; -declare const CKM_DES_CBC: number; -declare const CKM_DES_MAC: number; -declare const CKM_DES_MAC_GENERAL: number; -declare const CKM_DES_CBC_PAD: number; -declare const CKM_DES2_KEY_GEN: number; -declare const CKM_DES3_KEY_GEN: number; -declare const CKM_DES3_ECB: number; -declare const CKM_DES3_CBC: number; -declare const CKM_DES3_MAC: number; -declare const CKM_DES3_MAC_GENERAL: number; -declare const CKM_DES3_CBC_PAD: number; -declare const CKM_DES3_CMAC_GENERAL: number; -declare const CKM_DES3_CMAC: number; -declare const CKM_CDMF_KEY_GEN: number; -declare const CKM_CDMF_ECB: number; -declare const CKM_CDMF_CBC: number; -declare const CKM_CDMF_MAC: number; -declare const CKM_CDMF_MAC_GENERAL: number; -declare const CKM_CDMF_CBC_PAD: number; -declare const CKM_DES_OFB64: number; -declare const CKM_DES_OFB8: number; -declare const CKM_DES_CFB64: number; -declare const CKM_DES_CFB8: number; -declare const CKM_MD2: number; -declare const CKM_MD2_HMAC: number; -declare const CKM_MD2_HMAC_GENERAL: number; -declare const CKM_MD5: number; -declare const CKM_MD5_HMAC: number; -declare const CKM_MD5_HMAC_GENERAL: number; -declare const CKM_SHA_1: number; -declare const CKM_SHA_1_HMAC: number; -declare const CKM_SHA_1_HMAC_GENERAL: number; -declare const CKM_RIPEMD128: number; -declare const CKM_RIPEMD128_HMAC: number; -declare const CKM_RIPEMD128_HMAC_GENERAL: number; -declare const CKM_RIPEMD160: number; -declare const CKM_RIPEMD160_HMAC: number; -declare const CKM_RIPEMD160_HMAC_GENERAL: number; -declare const CKM_SHA256: number; -declare const CKM_SHA256_HMAC: number; -declare const CKM_SHA256_HMAC_GENERAL: number; -declare const CKM_SHA224: number; -declare const CKM_SHA224_HMAC: number; -declare const CKM_SHA224_HMAC_GENERAL: number; -declare const CKM_SHA384: number; -declare const CKM_SHA384_HMAC: number; -declare const CKM_SHA384_HMAC_GENERAL: number; -declare const CKM_SHA512: number; -declare const CKM_SHA512_HMAC: number; -declare const CKM_SHA512_HMAC_GENERAL: number; -declare const CKM_SECURID_KEY_GEN: number; -declare const CKM_SECURID: number; -declare const CKM_HOTP_KEY_GEN: number; -declare const CKM_HOTP: number; -declare const CKM_ACTI: number; -declare const CKM_ACTI_KEY_GEN: number; -declare const CKM_CAST_KEY_GEN: number; -declare const CKM_CAST_ECB: number; -declare const CKM_CAST_CBC: number; -declare const CKM_CAST_MAC: number; -declare const CKM_CAST_MAC_GENERAL: number; -declare const CKM_CAST_CBC_PAD: number; -declare const CKM_CAST3_KEY_GEN: number; -declare const CKM_CAST3_ECB: number; -declare const CKM_CAST3_CBC: number; -declare const CKM_CAST3_MAC: number; -declare const CKM_CAST3_MAC_GENERAL: number; -declare const CKM_CAST3_CBC_PAD: number; -declare const CKM_CAST5_KEY_GEN: number; -declare const CKM_CAST128_KEY_GEN: number; -declare const CKM_CAST5_ECB: number; -declare const CKM_CAST128_ECB: number; -declare const CKM_CAST5_CBC: number; -declare const CKM_CAST128_CBC: number; -declare const CKM_CAST5_MAC: number; -declare const CKM_CAST128_MAC: number; -declare const CKM_CAST5_MAC_GENERAL: number; -declare const CKM_CAST128_MAC_GENERAL: number; -declare const CKM_CAST5_CBC_PAD: number; -declare const CKM_CAST128_CBC_PAD: number; -declare const CKM_RC5_KEY_GEN: number; -declare const CKM_RC5_ECB: number; -declare const CKM_RC5_CBC: number; -declare const CKM_RC5_MAC: number; -declare const CKM_RC5_MAC_GENERAL: number; -declare const CKM_RC5_CBC_PAD: number; -declare const CKM_IDEA_KEY_GEN: number; -declare const CKM_IDEA_ECB: number; -declare const CKM_IDEA_CBC: number; -declare const CKM_IDEA_MAC: number; -declare const CKM_IDEA_MAC_GENERAL: number; -declare const CKM_IDEA_CBC_PAD: number; -declare const CKM_GENERIC_SECRET_KEY_GEN: number; -declare const CKM_CONCATENATE_BASE_AND_KEY: number; -declare const CKM_CONCATENATE_BASE_AND_DATA: number; -declare const CKM_CONCATENATE_DATA_AND_BASE: number; -declare const CKM_XOR_BASE_AND_DATA: number; -declare const CKM_EXTRACT_KEY_FROM_KEY: number; -declare const CKM_SSL3_PRE_MASTER_KEY_GEN: number; -declare const CKM_SSL3_MASTER_KEY_DERIVE: number; -declare const CKM_SSL3_KEY_AND_MAC_DERIVE: number; -declare const CKM_SSL3_MASTER_KEY_DERIVE_DH: number; -declare const CKM_TLS_PRE_MASTER_KEY_GEN: number; -declare const CKM_TLS_MASTER_KEY_DERIVE: number; -declare const CKM_TLS_KEY_AND_MAC_DERIVE: number; -declare const CKM_TLS_MASTER_KEY_DERIVE_DH: number; -declare const CKM_TLS_PRF: number; -declare const CKM_SSL3_MD5_MAC: number; -declare const CKM_SSL3_SHA1_MAC: number; -declare const CKM_MD5_KEY_DERIVATION: number; -declare const CKM_MD2_KEY_DERIVATION: number; -declare const CKM_SHA1_KEY_DERIVATION: number; -declare const CKM_SHA256_KEY_DERIVATION: number; -declare const CKM_SHA384_KEY_DERIVATION: number; -declare const CKM_SHA512_KEY_DERIVATION: number; -declare const CKM_SHA224_KEY_DERIVATION: number; -declare const CKM_PBE_MD2_DES_CBC: number; -declare const CKM_PBE_MD5_DES_CBC: number; -declare const CKM_PBE_MD5_CAST_CBC: number; -declare const CKM_PBE_MD5_CAST3_CBC: number; -declare const CKM_PBE_MD5_CAST5_CBC: number; -declare const CKM_PBE_MD5_CAST128_CBC: number; -declare const CKM_PBE_SHA1_CAST5_CBC: number; -declare const CKM_PBE_SHA1_CAST128_CBC: number; -declare const CKM_PBE_SHA1_RC4_128: number; -declare const CKM_PBE_SHA1_RC4_40: number; -declare const CKM_PBE_SHA1_DES3_EDE_CBC: number; -declare const CKM_PBE_SHA1_DES2_EDE_CBC: number; -declare const CKM_PBE_SHA1_RC2_128_CBC: number; -declare const CKM_PBE_SHA1_RC2_40_CBC: number; -declare const CKM_PKCS5_PBKD2: number; -declare const CKM_PBA_SHA1_WITH_SHA1_HMAC: number; -declare const CKM_WTLS_PRE_MASTER_KEY_GEN: number; -declare const CKM_WTLS_MASTER_KEY_DERIVE: number; -declare const CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: number; -declare const CKM_WTLS_PRF: number; -declare const CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: number; -declare const CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: number; -declare const CKM_KEY_WRAP_LYNKS: number; -declare const CKM_KEY_WRAP_SET_OAEP: number; -declare const CKM_CAMELLIA_KEY_GEN: number; -declare const CKM_CAMELLIA_ECB: number; -declare const CKM_CAMELLIA_CBC: number; -declare const CKM_CAMELLIA_MAC: number; -declare const CKM_CAMELLIA_MAC_GENERAL: number; -declare const CKM_CAMELLIA_CBC_PAD: number; -declare const CKM_CAMELLIA_ECB_ENCRYPT_DATA: number; -declare const CKM_CAMELLIA_CBC_ENCRYPT_DATA: number; -declare const CKM_CAMELLIA_CTR: number; -declare const CKM_ARIA_KEY_GEN: number; -declare const CKM_ARIA_ECB: number; -declare const CKM_ARIA_CBC: number; -declare const CKM_ARIA_MAC: number; -declare const CKM_ARIA_MAC_GENERAL: number; -declare const CKM_ARIA_CBC_PAD: number; -declare const CKM_ARIA_ECB_ENCRYPT_DATA: number; -declare const CKM_ARIA_CBC_ENCRYPT_DATA: number; -declare const CKM_SEED_KEY_GEN: number; -declare const CKM_SEED_ECB: number; -declare const CKM_SEED_CBC: number; -declare const CKM_SEED_MAC: number; -declare const CKM_SEED_MAC_GENERAL: number; -declare const CKM_SEED_CBC_PAD: number; -declare const CKM_SEED_ECB_ENCRYPT_DATA: number; -declare const CKM_SEED_CBC_ENCRYPT_DATA: number; -declare const CKM_SKIPJACK_KEY_GEN: number; -declare const CKM_SKIPJACK_ECB64: number; -declare const CKM_SKIPJACK_CBC64: number; -declare const CKM_SKIPJACK_OFB64: number; -declare const CKM_SKIPJACK_CFB64: number; -declare const CKM_SKIPJACK_CFB32: number; -declare const CKM_SKIPJACK_CFB16: number; -declare const CKM_SKIPJACK_CFB8: number; -declare const CKM_SKIPJACK_WRAP: number; -declare const CKM_SKIPJACK_PRIVATE_WRAP: number; -declare const CKM_SKIPJACK_RELAYX: number; -declare const CKM_KEA_KEY_PAIR_GEN: number; -declare const CKM_KEA_KEY_DERIVE: number; -declare const CKM_FORTEZZA_TIMESTAMP: number; -declare const CKM_BATON_KEY_GEN: number; -declare const CKM_BATON_ECB128: number; -declare const CKM_BATON_ECB96: number; -declare const CKM_BATON_CBC128: number; -declare const CKM_BATON_COUNTER: number; -declare const CKM_BATON_SHUFFLE: number; -declare const CKM_BATON_WRAP: number; -declare const CKM_ECDSA_KEY_PAIR_GEN: number; -declare const CKM_EC_KEY_PAIR_GEN: number; -declare const CKM_ECDSA: number; -declare const CKM_ECDSA_SHA1: number; -declare const CKM_ECDSA_SHA224: number; -declare const CKM_ECDSA_SHA256: number; -declare const CKM_ECDSA_SHA384: number; -declare const CKM_ECDSA_SHA512: number; -declare const CKM_ECDH1_DERIVE: number; -declare const CKM_ECDH1_COFACTOR_DERIVE: number; -declare const CKM_ECMQV_DERIVE: number; -declare const CKM_JUNIPER_KEY_GEN: number; -declare const CKM_JUNIPER_ECB128: number; -declare const CKM_JUNIPER_CBC128: number; -declare const CKM_JUNIPER_COUNTER: number; -declare const CKM_JUNIPER_SHUFFLE: number; -declare const CKM_JUNIPER_WRAP: number; -declare const CKM_FASTHASH: number; -declare const CKM_AES_KEY_GEN: number; -declare const CKM_AES_ECB: number; -declare const CKM_AES_CBC: number; -declare const CKM_AES_MAC: number; -declare const CKM_AES_MAC_GENERAL: number; -declare const CKM_AES_CBC_PAD: number; -declare const CKM_AES_CTR: number; -declare const CKM_AES_CTS: number; -declare const CKM_AES_CMAC: number; -declare const CKM_AES_CMAC_GENERAL: number; -declare const CKM_BLOWFISH_KEY_GEN: number; -declare const CKM_BLOWFISH_CBC: number; -declare const CKM_TWOFISH_KEY_GEN: number; -declare const CKM_TWOFISH_CBC: number; -declare const CKM_AES_GCM: number; -declare const CKM_AES_CCM: number; -declare const CKM_AES_KEY_WRAP: number; -declare const CKM_AES_KEY_WRAP_PAD: number; -declare const CKM_BLOWFISH_CBC_PAD: number; -declare const CKM_TWOFISH_CBC_PAD: number; -declare const CKM_DES_ECB_ENCRYPT_DATA: number; -declare const CKM_DES_CBC_ENCRYPT_DATA: number; -declare const CKM_DES3_ECB_ENCRYPT_DATA: number; -declare const CKM_DES3_CBC_ENCRYPT_DATA: number; -declare const CKM_AES_ECB_ENCRYPT_DATA: number; -declare const CKM_AES_CBC_ENCRYPT_DATA: number; -declare const CKM_GOSTR3410_KEY_PAIR_GEN: number; -declare const CKM_GOSTR3410: number; -declare const CKM_GOSTR3410_WITH_GOSTR3411: number; -declare const CKM_GOSTR3410_KEY_WRAP: number; -declare const CKM_GOSTR3410_DERIVE: number; -declare const CKM_GOSTR3411: number; -declare const CKM_GOSTR3411_HMAC: number; -declare const CKM_GOST28147_KEY_GEN: number; -declare const CKM_GOST28147_ECB: number; -declare const CKM_GOST28147: number; -declare const CKM_GOST28147_MAC: number; -declare const CKM_GOST28147_KEY_WRAP: number; -declare const CKM_DSA_PARAMETER_GEN: number; -declare const CKM_DH_PKCS_PARAMETER_GEN: number; -declare const CKM_X9_42_DH_PARAMETER_GEN: number; -declare const CKM_AES_OFB: number; -declare const CKM_AES_CFB64: number; -declare const CKM_AES_CFB8: number; -declare const CKM_AES_CFB128: number; -declare const CKM_RSA_PKCS_TPM_1_1: number; -declare const CKM_RSA_PKCS_OAEP_TPM_1_1: number; -declare const CKM_VENDOR_DEFINED: number; + // Mechanism + const CKM_RSA_PKCS_KEY_PAIR_GEN: number; + const CKM_RSA_PKCS: number; + const CKM_RSA_9796: number; + const CKM_RSA_X_509: number; + const CKM_MD2_RSA_PKCS: number; + const CKM_MD5_RSA_PKCS: number; + const CKM_SHA1_RSA_PKCS: number; + const CKM_RIPEMD128_RSA_PKCS: number; + const CKM_RIPEMD160_RSA_PKCS: number; + const CKM_RSA_PKCS_OAEP: number; + const CKM_RSA_X9_31_KEY_PAIR_GEN: number; + const CKM_RSA_X9_31: number; + const CKM_SHA1_RSA_X9_31: number; + const CKM_RSA_PKCS_PSS: number; + const CKM_SHA1_RSA_PKCS_PSS: number; + const CKM_DSA_KEY_PAIR_GEN: number; + const CKM_DSA: number; + const CKM_DSA_SHA1: number; + const CKM_DSA_SHA224: number; + const CKM_DSA_SHA256: number; + const CKM_DSA_SHA384: number; + const CKM_DSA_SHA512: number; + const CKM_DH_PKCS_KEY_PAIR_GEN: number; + const CKM_DH_PKCS_DERIVE: number; + const CKM_X9_42_DH_KEY_PAIR_GEN: number; + const CKM_X9_42_DH_DERIVE: number; + const CKM_X9_42_DH_HYBRID_DERIVE: number; + const CKM_X9_42_MQV_DERIVE: number; + const CKM_SHA256_RSA_PKCS: number; + const CKM_SHA384_RSA_PKCS: number; + const CKM_SHA512_RSA_PKCS: number; + const CKM_SHA256_RSA_PKCS_PSS: number; + const CKM_SHA384_RSA_PKCS_PSS: number; + const CKM_SHA512_RSA_PKCS_PSS: number; + const CKM_SHA224_RSA_PKCS: number; + const CKM_SHA224_RSA_PKCS_PSS: number; + const CKM_RC2_KEY_GEN: number; + const CKM_RC2_ECB: number; + const CKM_RC2_CBC: number; + const CKM_RC2_MAC: number; + const CKM_RC2_MAC_GENERAL: number; + const CKM_RC2_CBC_PAD: number; + const CKM_RC4_KEY_GEN: number; + const CKM_RC4: number; + const CKM_DES_KEY_GEN: number; + const CKM_DES_ECB: number; + const CKM_DES_CBC: number; + const CKM_DES_MAC: number; + const CKM_DES_MAC_GENERAL: number; + const CKM_DES_CBC_PAD: number; + const CKM_DES2_KEY_GEN: number; + const CKM_DES3_KEY_GEN: number; + const CKM_DES3_ECB: number; + const CKM_DES3_CBC: number; + const CKM_DES3_MAC: number; + const CKM_DES3_MAC_GENERAL: number; + const CKM_DES3_CBC_PAD: number; + const CKM_DES3_CMAC_GENERAL: number; + const CKM_DES3_CMAC: number; + const CKM_CDMF_KEY_GEN: number; + const CKM_CDMF_ECB: number; + const CKM_CDMF_CBC: number; + const CKM_CDMF_MAC: number; + const CKM_CDMF_MAC_GENERAL: number; + const CKM_CDMF_CBC_PAD: number; + const CKM_DES_OFB64: number; + const CKM_DES_OFB8: number; + const CKM_DES_CFB64: number; + const CKM_DES_CFB8: number; + const CKM_MD2: number; + const CKM_MD2_HMAC: number; + const CKM_MD2_HMAC_GENERAL: number; + const CKM_MD5: number; + const CKM_MD5_HMAC: number; + const CKM_MD5_HMAC_GENERAL: number; + const CKM_SHA_1: number; + const CKM_SHA_1_HMAC: number; + const CKM_SHA_1_HMAC_GENERAL: number; + const CKM_RIPEMD128: number; + const CKM_RIPEMD128_HMAC: number; + const CKM_RIPEMD128_HMAC_GENERAL: number; + const CKM_RIPEMD160: number; + const CKM_RIPEMD160_HMAC: number; + const CKM_RIPEMD160_HMAC_GENERAL: number; + const CKM_SHA256: number; + const CKM_SHA256_HMAC: number; + const CKM_SHA256_HMAC_GENERAL: number; + const CKM_SHA224: number; + const CKM_SHA224_HMAC: number; + const CKM_SHA224_HMAC_GENERAL: number; + const CKM_SHA384: number; + const CKM_SHA384_HMAC: number; + const CKM_SHA384_HMAC_GENERAL: number; + const CKM_SHA512: number; + const CKM_SHA512_HMAC: number; + const CKM_SHA512_HMAC_GENERAL: number; + const CKM_SECURID_KEY_GEN: number; + const CKM_SECURID: number; + const CKM_HOTP_KEY_GEN: number; + const CKM_HOTP: number; + const CKM_ACTI: number; + const CKM_ACTI_KEY_GEN: number; + const CKM_CAST_KEY_GEN: number; + const CKM_CAST_ECB: number; + const CKM_CAST_CBC: number; + const CKM_CAST_MAC: number; + const CKM_CAST_MAC_GENERAL: number; + const CKM_CAST_CBC_PAD: number; + const CKM_CAST3_KEY_GEN: number; + const CKM_CAST3_ECB: number; + const CKM_CAST3_CBC: number; + const CKM_CAST3_MAC: number; + const CKM_CAST3_MAC_GENERAL: number; + const CKM_CAST3_CBC_PAD: number; + const CKM_CAST5_KEY_GEN: number; + const CKM_CAST128_KEY_GEN: number; + const CKM_CAST5_ECB: number; + const CKM_CAST128_ECB: number; + const CKM_CAST5_CBC: number; + const CKM_CAST128_CBC: number; + const CKM_CAST5_MAC: number; + const CKM_CAST128_MAC: number; + const CKM_CAST5_MAC_GENERAL: number; + const CKM_CAST128_MAC_GENERAL: number; + const CKM_CAST5_CBC_PAD: number; + const CKM_CAST128_CBC_PAD: number; + const CKM_RC5_KEY_GEN: number; + const CKM_RC5_ECB: number; + const CKM_RC5_CBC: number; + const CKM_RC5_MAC: number; + const CKM_RC5_MAC_GENERAL: number; + const CKM_RC5_CBC_PAD: number; + const CKM_IDEA_KEY_GEN: number; + const CKM_IDEA_ECB: number; + const CKM_IDEA_CBC: number; + const CKM_IDEA_MAC: number; + const CKM_IDEA_MAC_GENERAL: number; + const CKM_IDEA_CBC_PAD: number; + const CKM_GENERIC_SECRET_KEY_GEN: number; + const CKM_CONCATENATE_BASE_AND_KEY: number; + const CKM_CONCATENATE_BASE_AND_DATA: number; + const CKM_CONCATENATE_DATA_AND_BASE: number; + const CKM_XOR_BASE_AND_DATA: number; + const CKM_EXTRACT_KEY_FROM_KEY: number; + const CKM_SSL3_PRE_MASTER_KEY_GEN: number; + const CKM_SSL3_MASTER_KEY_DERIVE: number; + const CKM_SSL3_KEY_AND_MAC_DERIVE: number; + const CKM_SSL3_MASTER_KEY_DERIVE_DH: number; + const CKM_TLS_PRE_MASTER_KEY_GEN: number; + const CKM_TLS_MASTER_KEY_DERIVE: number; + const CKM_TLS_KEY_AND_MAC_DERIVE: number; + const CKM_TLS_MASTER_KEY_DERIVE_DH: number; + const CKM_TLS_PRF: number; + const CKM_SSL3_MD5_MAC: number; + const CKM_SSL3_SHA1_MAC: number; + const CKM_MD5_KEY_DERIVATION: number; + const CKM_MD2_KEY_DERIVATION: number; + const CKM_SHA1_KEY_DERIVATION: number; + const CKM_SHA256_KEY_DERIVATION: number; + const CKM_SHA384_KEY_DERIVATION: number; + const CKM_SHA512_KEY_DERIVATION: number; + const CKM_SHA224_KEY_DERIVATION: number; + const CKM_PBE_MD2_DES_CBC: number; + const CKM_PBE_MD5_DES_CBC: number; + const CKM_PBE_MD5_CAST_CBC: number; + const CKM_PBE_MD5_CAST3_CBC: number; + const CKM_PBE_MD5_CAST5_CBC: number; + const CKM_PBE_MD5_CAST128_CBC: number; + const CKM_PBE_SHA1_CAST5_CBC: number; + const CKM_PBE_SHA1_CAST128_CBC: number; + const CKM_PBE_SHA1_RC4_128: number; + const CKM_PBE_SHA1_RC4_40: number; + const CKM_PBE_SHA1_DES3_EDE_CBC: number; + const CKM_PBE_SHA1_DES2_EDE_CBC: number; + const CKM_PBE_SHA1_RC2_128_CBC: number; + const CKM_PBE_SHA1_RC2_40_CBC: number; + const CKM_PKCS5_PBKD2: number; + const CKM_PBA_SHA1_WITH_SHA1_HMAC: number; + const CKM_WTLS_PRE_MASTER_KEY_GEN: number; + const CKM_WTLS_MASTER_KEY_DERIVE: number; + const CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: number; + const CKM_WTLS_PRF: number; + const CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: number; + const CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: number; + const CKM_KEY_WRAP_LYNKS: number; + const CKM_KEY_WRAP_SET_OAEP: number; + const CKM_CAMELLIA_KEY_GEN: number; + const CKM_CAMELLIA_ECB: number; + const CKM_CAMELLIA_CBC: number; + const CKM_CAMELLIA_MAC: number; + const CKM_CAMELLIA_MAC_GENERAL: number; + const CKM_CAMELLIA_CBC_PAD: number; + const CKM_CAMELLIA_ECB_ENCRYPT_DATA: number; + const CKM_CAMELLIA_CBC_ENCRYPT_DATA: number; + const CKM_CAMELLIA_CTR: number; + const CKM_ARIA_KEY_GEN: number; + const CKM_ARIA_ECB: number; + const CKM_ARIA_CBC: number; + const CKM_ARIA_MAC: number; + const CKM_ARIA_MAC_GENERAL: number; + const CKM_ARIA_CBC_PAD: number; + const CKM_ARIA_ECB_ENCRYPT_DATA: number; + const CKM_ARIA_CBC_ENCRYPT_DATA: number; + const CKM_SEED_KEY_GEN: number; + const CKM_SEED_ECB: number; + const CKM_SEED_CBC: number; + const CKM_SEED_MAC: number; + const CKM_SEED_MAC_GENERAL: number; + const CKM_SEED_CBC_PAD: number; + const CKM_SEED_ECB_ENCRYPT_DATA: number; + const CKM_SEED_CBC_ENCRYPT_DATA: number; + const CKM_SKIPJACK_KEY_GEN: number; + const CKM_SKIPJACK_ECB64: number; + const CKM_SKIPJACK_CBC64: number; + const CKM_SKIPJACK_OFB64: number; + const CKM_SKIPJACK_CFB64: number; + const CKM_SKIPJACK_CFB32: number; + const CKM_SKIPJACK_CFB16: number; + const CKM_SKIPJACK_CFB8: number; + const CKM_SKIPJACK_WRAP: number; + const CKM_SKIPJACK_PRIVATE_WRAP: number; + const CKM_SKIPJACK_RELAYX: number; + const CKM_KEA_KEY_PAIR_GEN: number; + const CKM_KEA_KEY_DERIVE: number; + const CKM_FORTEZZA_TIMESTAMP: number; + const CKM_BATON_KEY_GEN: number; + const CKM_BATON_ECB128: number; + const CKM_BATON_ECB96: number; + const CKM_BATON_CBC128: number; + const CKM_BATON_COUNTER: number; + const CKM_BATON_SHUFFLE: number; + const CKM_BATON_WRAP: number; + const CKM_ECDSA_KEY_PAIR_GEN: number; + const CKM_EC_KEY_PAIR_GEN: number; + const CKM_ECDSA: number; + const CKM_ECDSA_SHA1: number; + const CKM_ECDSA_SHA224: number; + const CKM_ECDSA_SHA256: number; + const CKM_ECDSA_SHA384: number; + const CKM_ECDSA_SHA512: number; + const CKM_ECDH1_DERIVE: number; + const CKM_ECDH1_COFACTOR_DERIVE: number; + const CKM_ECMQV_DERIVE: number; + const CKM_JUNIPER_KEY_GEN: number; + const CKM_JUNIPER_ECB128: number; + const CKM_JUNIPER_CBC128: number; + const CKM_JUNIPER_COUNTER: number; + const CKM_JUNIPER_SHUFFLE: number; + const CKM_JUNIPER_WRAP: number; + const CKM_FASTHASH: number; + const CKM_AES_KEY_GEN: number; + const CKM_AES_ECB: number; + const CKM_AES_CBC: number; + const CKM_AES_MAC: number; + const CKM_AES_MAC_GENERAL: number; + const CKM_AES_CBC_PAD: number; + const CKM_AES_CTR: number; + const CKM_AES_CTS: number; + const CKM_AES_CMAC: number; + const CKM_AES_CMAC_GENERAL: number; + const CKM_BLOWFISH_KEY_GEN: number; + const CKM_BLOWFISH_CBC: number; + const CKM_TWOFISH_KEY_GEN: number; + const CKM_TWOFISH_CBC: number; + const CKM_AES_GCM: number; + const CKM_AES_CCM: number; + const CKM_AES_KEY_WRAP: number; + const CKM_AES_KEY_WRAP_PAD: number; + const CKM_BLOWFISH_CBC_PAD: number; + const CKM_TWOFISH_CBC_PAD: number; + const CKM_DES_ECB_ENCRYPT_DATA: number; + const CKM_DES_CBC_ENCRYPT_DATA: number; + const CKM_DES3_ECB_ENCRYPT_DATA: number; + const CKM_DES3_CBC_ENCRYPT_DATA: number; + const CKM_AES_ECB_ENCRYPT_DATA: number; + const CKM_AES_CBC_ENCRYPT_DATA: number; + const CKM_GOSTR3410_KEY_PAIR_GEN: number; + const CKM_GOSTR3410: number; + const CKM_GOSTR3410_WITH_GOSTR3411: number; + const CKM_GOSTR3410_KEY_WRAP: number; + const CKM_GOSTR3410_DERIVE: number; + const CKM_GOSTR3411: number; + const CKM_GOSTR3411_HMAC: number; + const CKM_GOST28147_KEY_GEN: number; + const CKM_GOST28147_ECB: number; + const CKM_GOST28147: number; + const CKM_GOST28147_MAC: number; + const CKM_GOST28147_KEY_WRAP: number; + const CKM_DSA_PARAMETER_GEN: number; + const CKM_DH_PKCS_PARAMETER_GEN: number; + const CKM_X9_42_DH_PARAMETER_GEN: number; + const CKM_AES_OFB: number; + const CKM_AES_CFB64: number; + const CKM_AES_CFB8: number; + const CKM_AES_CFB128: number; + const CKM_RSA_PKCS_TPM_1_1: number; + const CKM_RSA_PKCS_OAEP_TPM_1_1: number; + const CKM_VENDOR_DEFINED: number; -// Session flags -declare const CKF_RW_SESSION: number; -declare const CKF_SERIAL_SESSION: number; + // Session flags + const CKF_RW_SESSION: number; + const CKF_SERIAL_SESSION: number; -// Follows -declare const CKF_HW: number; -declare const CKF_ENCRYPT: number; -declare const CKF_DECRYPT: number; -declare const CKF_DIGEST: number; -declare const CKF_SIGN: number; -declare const CKF_SIGN_RECOVER: number; -declare const CKF_VERIFY: number; -declare const CKF_VERIFY_RECOVER: number; -declare const CKF_GENERATE: number; -declare const CKF_GENERATE_KEY_PAIR: number; -declare const CKF_WRAP: number; -declare const CKF_UNWRAP: number; -declare const CKF_DERIVE: number; + // Follows + const CKF_HW: number; + const CKF_ENCRYPT: number; + const CKF_DECRYPT: number; + const CKF_DIGEST: number; + const CKF_SIGN: number; + const CKF_SIGN_RECOVER: number; + const CKF_VERIFY: number; + const CKF_VERIFY_RECOVER: number; + const CKF_GENERATE: number; + const CKF_GENERATE_KEY_PAIR: number; + const CKF_WRAP: number; + const CKF_UNWRAP: number; + const CKF_DERIVE: number; -// Certificates -declare const CKC_X_509: number; -declare const CKC_X_509_ATTR_CERT: number; -declare const CKC_WTLS: number; + // Certificates + const CKC_X_509: number; + const CKC_X_509_ATTR_CERT: number; + const CKC_WTLS: number; -// MGFs -declare const CKG_MGF1_SHA1: number; -declare const CKG_MGF1_SHA256: number; -declare const CKG_MGF1_SHA384: number; -declare const CKG_MGF1_SHA512: number; -declare const CKG_MGF1_SHA224: number; + // MGFs + const CKG_MGF1_SHA1: number; + const CKG_MGF1_SHA256: number; + const CKG_MGF1_SHA384: number; + const CKG_MGF1_SHA512: number; + const CKG_MGF1_SHA224: number; -// KDFs -declare const CKD_NULL: number; -declare const CKD_SHA1_KDF: number; -declare const CKD_SHA1_KDF_ASN1: number; -declare const CKD_SHA1_KDF_CONCATENATE: number; -declare const CKD_SHA224_KDF: number; -declare const CKD_SHA256_KDF: number; -declare const CKD_SHA384_KDF: number; -declare const CKD_SHA512_KDF: number; -declare const CKD_CPDIVERSIFY_KDF: number; + // KDFs + const CKD_NULL: number; + const CKD_SHA1_KDF: number; + const CKD_SHA1_KDF_ASN1: number; + const CKD_SHA1_KDF_CONCATENATE: number; + const CKD_SHA224_KDF: number; + const CKD_SHA256_KDF: number; + const CKD_SHA384_KDF: number; + const CKD_SHA512_KDF: number; + const CKD_CPDIVERSIFY_KDF: number; -// Mech params -declare const CK_PARAMS_AES_CBC: number; -declare const CK_PARAMS_AES_CCM: number; -declare const CK_PARAMS_AES_GCM: number; -declare const CK_PARAMS_RSA_OAEP: number; -declare const CK_PARAMS_RSA_PSS: number; -declare const CK_PARAMS_EC_DH: number; + // Mech params + const CK_PARAMS_AES_CBC: number; + const CK_PARAMS_AES_CCM: number; + const CK_PARAMS_AES_GCM: number; + const CK_PARAMS_RSA_OAEP: number; + const CK_PARAMS_RSA_PSS: number; + const CK_PARAMS_EC_DH: number; + +} \ No newline at end of file diff --git a/pkcs11js/tsconfig.json b/pkcs11js/tsconfig.json index 04983766e4..5945db50bb 100644 --- a/pkcs11js/tsconfig.json +++ b/pkcs11js/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 4c4aeebb1e33a5a86b7bb6def10e79b1fc7f2ae2 Mon Sep 17 00:00:00 2001 From: Tadas Dailyda Date: Wed, 2 Nov 2016 17:16:32 +0200 Subject: [PATCH 041/131] react-css-modules: augment react's HTMLAttributes interface (#12184) * augment react's HTMLAttributes interface with styleName * move 'react-css-modules' declarations to top-level, turn on strictNullChecks --- react-css-modules/index.d.ts | 44 +++++++++++++++++---------------- react-css-modules/tsconfig.json | 4 +-- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/react-css-modules/index.d.ts b/react-css-modules/index.d.ts index d8a414d35f..d709a69d73 100644 --- a/react-css-modules/index.d.ts +++ b/react-css-modules/index.d.ts @@ -1,33 +1,35 @@ // Type definitions for react-css-modules 3.7.9 // Project: https://github.com/gajus/react-css-modules -// Definitions by: Kostya Esmukov +// Definitions by: Kostya Esmukov , Tadas Dailyda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface TypeOptions { + allowMultiple?: boolean; + errorWhenNotFound?: boolean; +} -declare module 'react-css-modules' { +type StylesObject = any; - interface TypeOptions { - allowMultiple?: boolean; - errorWhenNotFound?: boolean; +interface CSSModules { + (defaultStyles: StylesObject, options?: TypeOptions): (Component: C) => C; + (Component: C, defaultStyles: StylesObject, options?: TypeOptions): C; +} + +declare module CSSModules { + // Extend your component's Prop interface with this one to get access to `this.props.styles` + // + // interface MyComponentProps extends CSSModules.InjectedCSSModuleProps {} + interface InjectedCSSModuleProps { + styles?: StylesObject; } +} - type StylesObject = any; +declare let CSSModules: CSSModules; - interface CSSModules { - (defaultStyles: StylesObject, options?: TypeOptions): (Component: C) => C; - (Component: C, defaultStyles: StylesObject, options?: TypeOptions): C; - } +export = CSSModules; - module CSSModules { - // Extend your component's Prop interface with this one to get access to `this.props.styles` - // - // interface MyComponentProps extends CSSModules.InjectedCSSModuleProps {} - interface InjectedCSSModuleProps { - styles?: StylesObject; - } +declare module 'react' { + interface HTMLAttributes { + styleName?: string; } - - let CSSModules: CSSModules; - - export = CSSModules; } diff --git a/react-css-modules/tsconfig.json b/react-css-modules/tsconfig.json index 79b9eb6b27..f4ba62c160 100644 --- a/react-css-modules/tsconfig.json +++ b/react-css-modules/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -15,4 +15,4 @@ "files": [ "index.d.ts" ] -} \ No newline at end of file +} From c5ea2b4c69f6f6a8f8346645630c805773f628b1 Mon Sep 17 00:00:00 2001 From: Connor Peet Date: Tue, 1 Nov 2016 09:06:04 -0700 Subject: [PATCH 042/131] Treat clipboard as a CJS module --- clipboard/clipboard-tests.ts | 2 +- clipboard/index.d.ts | 98 ++++++++++++++++++------------------ 2 files changed, 51 insertions(+), 49 deletions(-) diff --git a/clipboard/clipboard-tests.ts b/clipboard/clipboard-tests.ts index c6c7b756cb..7521c651dd 100644 --- a/clipboard/clipboard-tests.ts +++ b/clipboard/clipboard-tests.ts @@ -1,4 +1,4 @@ - +import * as Clipboard from 'clipboard'; var cb1 = new Clipboard('.btn'); var cb2 = new Clipboard(document.getElementById('id'), { diff --git a/clipboard/index.d.ts b/clipboard/index.d.ts index d4b014e2f3..0757eb1208 100644 --- a/clipboard/index.d.ts +++ b/clipboard/index.d.ts @@ -3,54 +3,56 @@ // Definitions by: Andrei Kurosh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Clipboard { - constructor(selector: (string | Element | NodeListOf), options?: ClipboardOptions); - - /** - * Subscribes to events that indicate the result of a copy/cut operation. - * @param type {String} Event type ('success' or 'error'). - * @param handler Callback function. - */ - on(type: "success", handler: (e: ClipboardEvent) => void): this; - on(type: "error", handler: (e: ClipboardEvent) => void): this; - on(type: string, handler: (e: ClipboardEvent) => void): this; - - /** - * Clears all event bindings. - */ - destroy(): void; -} - -interface ClipboardOptions { - /** - * Overwrites default command ('cut' or 'copy'). - * @param {Element} elem Current element - * @returns {String} Only 'cut' or 'copy'. - */ - action?: (elem: Element) => string; - - /** - * Overwrites default target input element. - * @param {Element} elem Current element - * @returns {Element} element to use. - */ - target?: (elem: Element) => Element; - - /** - * Returns the explicit text to copy. - * @param {Element} elem Current element - * @returns {String} Text to be copied. - */ - text?: (elem: Element) => string; -} - -interface ClipboardEvent { - action: string; - text: string; - trigger: Element; - clearSelection(): void; -} - declare module 'clipboard' { + class Clipboard { + constructor(selector: (string | Element | NodeListOf), options?: Clipboard.Options); + + /** + * Subscribes to events that indicate the result of a copy/cut operation. + * @param type {String} Event type ('success' or 'error'). + * @param handler Callback function. + */ + on(type: "success", handler: (e: Clipboard.Event) => void): this; + on(type: "error", handler: (e: Clipboard.Event) => void): this; + on(type: string, handler: (e: Clipboard.Event) => void): this; + + /** + * Clears all event bindings. + */ + destroy(): void; + } + + namespace Clipboard { + interface Options { + /** + * Overwrites default command ('cut' or 'copy'). + * @param {Element} elem Current element + * @returns {String} Only 'cut' or 'copy'. + */ + action?: (elem: Element) => string; + + /** + * Overwrites default target input element. + * @param {Element} elem Current element + * @returns {Element} element to use. + */ + target?: (elem: Element) => Element; + + /** + * Returns the explicit text to copy. + * @param {Element} elem Current element + * @returns {String} Text to be copied. + */ + text?: (elem: Element) => string; + } + + interface Event { + action: string; + text: string; + trigger: Element; + clearSelection(): void; + } + } + export = Clipboard; } From 9ba58624e814fcb09e4f1b19ef38406083c5f509 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 2 Nov 2016 09:41:50 -0700 Subject: [PATCH 043/131] Convert highcharts definition to module style --- highcharts-ng/index.d.ts | 70 +++--- highcharts/highcharts-modules-boost.d.ts | 4 +- highcharts/highcharts-modules-exporting.d.ts | 4 +- ...charts-modules-no-data-to-display-tests.ts | 1 - ...highcharts-modules-no-data-to-display.d.ts | 6 +- .../highcharts-modules-offline-exporting.d.ts | 4 +- highcharts/highcharts-more.d.ts | 4 +- highcharts/highcharts-tests.ts | 232 +++++++++--------- highcharts/highstock-tests.ts | 4 +- highcharts/highstock.d.ts | 26 +- highcharts/index.d.ts | 61 +++-- highcharts/tsconfig.json | 1 + 12 files changed, 208 insertions(+), 209 deletions(-) diff --git a/highcharts-ng/index.d.ts b/highcharts-ng/index.d.ts index eed6dde0db..123799e76c 100644 --- a/highcharts-ng/index.d.ts +++ b/highcharts-ng/index.d.ts @@ -3,41 +3,43 @@ // Definitions by: Scott Hatcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { ChartObject, IndividualSeriesOptions, Options } from "highcharts"; -interface HighChartsNGConfig { - options: __Highcharts.Options; - //The below properties are watched separately for changes. +declare global { + interface HighChartsNGConfig { + options: Options; + //The below properties are watched separately for changes. - //Series object (optional) - a list of series using normal highcharts series options. - series?: __Highcharts.IndividualSeriesOptions[]; - //Title configuration (optional) - title?: { - text?: string; - }; - //Boolean to control showng loading status on chart (optional) - //Could be a string if you want to show specific loading text. - loading?: boolean | string; - //Configuration for the xAxis (optional). Currently only one x axis can be dynamically controlled. - //properties currentMin and currentMax provied 2-way binding to the chart's maximimum and minimum - xAxis?: { - currentMin?: number; - currentMax?: number; - title?: { text?: string } - }; - //Whether to use HighStocks instead of HighCharts (optional). Defaults to false. - useHighStocks?: boolean; - //size (optional) if left out the chart will default to size of the div or something sensible. - size?: { - width?: number; - height?: number; - }; - //function (optional) - setup some logic for the chart - func?: (chart: __Highcharts.ChartObject) => void; -} + //Series object (optional) - a list of series using normal highcharts series options. + series?: IndividualSeriesOptions[]; + //Title configuration (optional) + title?: { + text?: string; + }; + //Boolean to control showng loading status on chart (optional) + //Could be a string if you want to show specific loading text. + loading?: boolean | string; + //Configuration for the xAxis (optional). Currently only one x axis can be dynamically controlled. + //properties currentMin and currentMax provied 2-way binding to the chart's maximimum and minimum + xAxis?: { + currentMin?: number; + currentMax?: number; + title?: { text?: string } + }; + //Whether to use HighStocks instead of HighCharts (optional). Defaults to false. + useHighStocks?: boolean; + //size (optional) if left out the chart will default to size of the div or something sensible. + size?: { + width?: number; + height?: number; + }; + //function (optional) - setup some logic for the chart + func?: (chart: ChartObject) => void; + } -//Instantiated Chart -interface HighChartsNGChart extends HighChartsNGConfig { - //This is a simple way to access all the Highcharts API that is not currently managed by this directive. - getHighcharts(): __Highcharts.ChartObject; + //Instantiated Chart + interface HighChartsNGChart extends HighChartsNGConfig { + //This is a simple way to access all the Highcharts API that is not currently managed by this directive. + getHighcharts(): ChartObject; + } } diff --git a/highcharts/highcharts-modules-boost.d.ts b/highcharts/highcharts-modules-boost.d.ts index 0991884558..5670df007b 100644 --- a/highcharts/highcharts-modules-boost.d.ts +++ b/highcharts/highcharts-modules-boost.d.ts @@ -3,9 +3,9 @@ // Definitions by: Daniel Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsBoost: (H: __Highcharts.Static) => __Highcharts.Static; +declare var HighchartsBoost: (H: Static) => Static; declare module "highcharts/modules/boost" { export = HighchartsBoost; diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts index b6a0e49f30..207e50ab8e 100644 --- a/highcharts/highcharts-modules-exporting.d.ts +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -3,9 +3,9 @@ // Definitions by: Maciej Suchecki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsExporting: (H: __Highcharts.Static) => __Highcharts.Static; +declare var HighchartsExporting: (H: Static) => Static; declare module "highcharts/modules/exporting" { export = HighchartsExporting; diff --git a/highcharts/highcharts-modules-no-data-to-display-tests.ts b/highcharts/highcharts-modules-no-data-to-display-tests.ts index 6c7b12e105..acd06d2f9f 100644 --- a/highcharts/highcharts-modules-no-data-to-display-tests.ts +++ b/highcharts/highcharts-modules-no-data-to-display-tests.ts @@ -1,5 +1,4 @@ /// -/// /// function test_NoDataToDisplay() { diff --git a/highcharts/highcharts-modules-no-data-to-display.d.ts b/highcharts/highcharts-modules-no-data-to-display.d.ts index db799236b4..0da068c413 100644 --- a/highcharts/highcharts-modules-no-data-to-display.d.ts +++ b/highcharts/highcharts-modules-no-data-to-display.d.ts @@ -2,8 +2,10 @@ // Project: http://www.highcharts.com/ // Definitions by: Andrey Zolotin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -declare namespace __Highcharts { + +import * as Hc from "highcharts"; + +declare module "highcharts" { interface ChartObject { /** * Returns true if there are data points within the plot area now diff --git a/highcharts/highcharts-modules-offline-exporting.d.ts b/highcharts/highcharts-modules-offline-exporting.d.ts index d0721c2d46..ff4de198ea 100644 --- a/highcharts/highcharts-modules-offline-exporting.d.ts +++ b/highcharts/highcharts-modules-offline-exporting.d.ts @@ -3,9 +3,9 @@ // Definitions by: Daniel Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsOfflineExporting: (H: __Highcharts.Static) => __Highcharts.Static; +declare var HighchartsOfflineExporting: (H: Static) => Static; declare module "highcharts/modules/offline-exporting" { export = HighchartsOfflineExporting; diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts index b80ce30f4a..b93b286563 100644 --- a/highcharts/highcharts-more.d.ts +++ b/highcharts/highcharts-more.d.ts @@ -3,9 +3,9 @@ // Definitions by: Maciej Suchecki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsMore: (H: __Highcharts.Static) => __Highcharts.Static; +declare var HighchartsMore: (H: Static) => Static; declare module "highcharts/highcharts-more" { export = HighchartsMore; diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index 31db25f482..459d812bcc 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -1,5 +1,5 @@ - /// +import * as Highcharts from "highcharts"; // May also use /// function originalTests() { Highcharts.setOptions({ @@ -16,13 +16,13 @@ function originalTests() { }); - var animate: __Highcharts.Animation = { + var animate: Highcharts.Animation = { duration: 200, easing: "linear" }; - var gradient: __Highcharts.Gradient = { + var gradient: Highcharts.Gradient = { linearGradient: { x1: 0, y1: 0, @@ -42,19 +42,19 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true }] }); - chart1.addSeries<__Highcharts.BarChartSeriesOptions>({ + chart1.addSeries({ enableMouseTracking: true, data: [1, 2, 3, 4, 5] }); - console.log((<__Highcharts.LineChartSeriesOptions>chart1.series[0].options).dashStyle); + console.log((chart1.series[0].options).dashStyle); var chart2 = new Highcharts.Chart({ chart: { @@ -85,7 +85,7 @@ function originalTests() { legend: { enabled: false }, - series: [<__Highcharts.ScatterChartSeriesOptions>{ + series: [{ data: [ [550, 870], [738, 362], [719, 711], [547, 665], [595, 197], [332, 144], [581, 555], [196, 862], [6, 837], [400, 924], [888, 148], [785, 730], @@ -113,14 +113,14 @@ function originalTests() { var r = new Highcharts.Renderer(div, 20, 30); var box = r.text("Hello", 10, 10).getBBox(); - var highChartSettings: __Highcharts.Options = { + var highChartSettings: Highcharts.Options = { chart: { width: 400, height: 400 }, xAxis: [{ }], - series: [<__Highcharts.PieChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }; @@ -129,16 +129,16 @@ function originalTests() { chart.series[0].setVisible(true, true); }); - var singleYAxisOptions: __Highcharts.Options = { + var singleYAxisOptions: Highcharts.Options = { yAxis: {} }; - var multipleYAxisOptions: __Highcharts.Options = { + var multipleYAxisOptions: Highcharts.Options = { yAxis: [{}, {}] }; var renderToIdChart = new Highcharts.Chart("container", { xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -147,7 +147,7 @@ function originalTests() { var renderToElementChart = new Highcharts.Chart(div, { xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -156,7 +156,7 @@ function originalTests() { var createWithFunction = Highcharts.chart({ xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -165,7 +165,7 @@ function originalTests() { var createWithFunctionRenderToId = Highcharts.chart("container", { xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -174,7 +174,7 @@ function originalTests() { var createWithFunctionRenderToElement = Highcharts.chart(div, { xAxis: {}, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -183,7 +183,7 @@ function originalTests() { } function test_alldefaults() { - var options: __Highcharts.Options = { + var options: Highcharts.Options = { chart: {}, credits: {}, data: {}, @@ -207,19 +207,19 @@ function test_alldefaults() { } function test_ChartOptions() { - var emptyChartOptions: __Highcharts.ChartOptions = { + var emptyChartOptions: Highcharts.ChartOptions = { events: {}, options3d: {}, resetZoomButton: {} }; - var allValuesSet: __Highcharts.ChartOptions = { + var allValuesSet: Highcharts.ChartOptions = { alignTicks: false, animation: { duration: 500, easing: "linear" }, - backgroundColor: <__Highcharts.Gradient> { + backgroundColor: { linearGradient: { x1: 0, y1: 0, @@ -233,7 +233,7 @@ function test_ChartOptions() { borderWidth: 5, className: "class", defaultSeriesType: "deprecated", - events: <__Highcharts.ChartEvents> { + events: { addSeries: () => {}, afterPrint: () => {}, beforePrint: () => {}, @@ -252,21 +252,21 @@ function test_ChartOptions() { marginLeft: 10, marginRight: 10, marginTop: 10, - options3d: <__Highcharts.ChartOptions3d> { + options3d: { alpha: 20, beta: 20, depth: 50, enabled: true, frame: { - back: <__Highcharts.ChartOptions3dFrame> { + back: { color: "black", size: 2 }, - bottom: <__Highcharts.ChartOptions3dFrame> { + bottom: { color: "black", size: 2 }, - side: <__Highcharts.ChartOptions3dFrame> { + side: { color: "black", size: 2 } @@ -280,7 +280,7 @@ function test_ChartOptions() { plotBackgroundImage: "http://image.url/image.jpg", plotBorderColor: "grey", plotBorderWidth: 5, - plotShadow: <__Highcharts.Shadow> { + plotShadow: { color: "magenta", offsetX: 10, offsetY: 10, @@ -290,15 +290,15 @@ function test_ChartOptions() { polar: true, reflow: false, renderTo: "elementId", - resetZoomButton: <__Highcharts.ChartResetZoomButton> { - position: <__Highcharts.Position> { + resetZoomButton: { + position: { align: "left", verticalAlign: "top", x: 5, y: 5 }, relativeTo: "chart", - theme: <__Highcharts.ButtonTheme> { + theme: { display: "hidden", fill: "black", stroke: "white", @@ -364,7 +364,7 @@ function test_ChartOptions() { }); // animation example - $('#container').highcharts(<__Highcharts.Options> { + $('#container').highcharts( { chart: { animation: { duration: 1500, @@ -449,7 +449,7 @@ function test_ChartOptions() { chart: { events: { addSeries: function () { - var label = (<__Highcharts.ChartObject>this).renderer.label('A series was added, about to redraw chart', 100, 120) + var label = (this).renderer.label('A series was added, about to redraw chart', 100, 120) .attr({ fill: Highcharts.getOptions().colors[0], padding: 10, @@ -578,7 +578,7 @@ function test_ChartOptions() { } function test_CreditsOptions() { - var allDefaults: __Highcharts.CreditsOptions = {}; + var allDefaults: Highcharts.CreditsOptions = {}; // custom url and text example $('#container').highcharts({ @@ -597,7 +597,7 @@ function test_CreditsOptions() { function test_Data() { // all defaults - var data: __Highcharts.DataOptions = {}; + var data: Highcharts.DataOptions = {}; // data from table example $('#container').highcharts({ @@ -631,10 +631,10 @@ function test_Data() { } }, series: [ - <__Highcharts.LineChartSeriesOptions> { + { lineWidth: 1 }, - <__Highcharts.AreaSplineChartSeriesOptions> { + { type: 'areaspline', color: '#c4392d', negativeColor: '#5679c4', @@ -645,7 +645,7 @@ function test_Data() { // limited data example $('#container').highcharts({ - data: <__Highcharts.DataOptions> { + data: { csv: document.getElementById('csv').innerHTML, startRow: 114, endRow: 134, @@ -655,7 +655,7 @@ function test_Data() { xAxis: { allowDecimals: false }, - series: [<__Highcharts.LineChartSeriesOptions> { + series: [ { name: 'Annual mean' }] }); @@ -675,7 +675,7 @@ function test_Data() { } function test_Drilldown() { - var allDefaults: __Highcharts.DrilldownOptions = {}; + var allDefaults: Highcharts.DrilldownOptions = {}; // multiseries drilldown example $('#container').highcharts({ @@ -686,14 +686,14 @@ function test_Drilldown() { type: 'category' }, plotOptions: { - series: <__Highcharts.ColumnChart> { + series: { borderWidth: 0, dataLabels: { enabled: true } } }, - series: [<__Highcharts.ColumnChartSeriesOptions>{ + series: [{ name: '2010', data: [{ name: 'Republican', @@ -708,7 +708,7 @@ function test_Drilldown() { y: 4, drilldown: 'other-2010' }] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { name: '2014', data: [{ name: 'Republican', @@ -725,7 +725,7 @@ function test_Drilldown() { }] }], drilldown: { - series: [<__Highcharts.ColumnChartSeriesOptions>{ + series: [{ id: 'republican-2010', data: [ ['East', 4], @@ -733,7 +733,7 @@ function test_Drilldown() { ['North', 1], ['South', 4] ] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { id: 'democrats-2010', data: [ ['East', 6], @@ -741,7 +741,7 @@ function test_Drilldown() { ['North', 2], ['South', 4] ] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { id: 'other-2010', data: [ ['East', 2], @@ -749,7 +749,7 @@ function test_Drilldown() { ['North', 3], ['South', 2] ] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { id: 'republican-2014', data: [ ['East', 2], @@ -757,7 +757,7 @@ function test_Drilldown() { ['North', 1], ['South', 7] ] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { id: 'democrats-2014', data: [ ['East', 4], @@ -765,7 +765,7 @@ function test_Drilldown() { ['North', 5], ['South', 3] ] - }, <__Highcharts.ColumnChartSeriesOptions>{ + }, { id: 'other-2014', data: [ ['East', 7], @@ -783,14 +783,14 @@ function test_Drilldown() { type: 'column' }, plotOptions: { - series: <__Highcharts.ColumnChart> { + series: { borderWidth: 0, dataLabels: { enabled: true } } }, - series: [<__Highcharts.ColumnChartSeriesOptions>{ + series: [{ name: 'Things', colorByPoint: true, data: [{ @@ -858,7 +858,7 @@ function test_Drilldown() { } function test_Exporting() { - var allDefaults: __Highcharts.ExportingOptions = {}; + var allDefaults: Highcharts.ExportingOptions = {}; // source size example $('#container').highcharts({ @@ -890,13 +890,13 @@ function test_Exporting() { } function test_Loading() { - var allDefaults: __Highcharts.LoadingOptions = {}; + var allDefaults: Highcharts.LoadingOptions = {}; // examples // the button handler var isLoading = false, $button = $('#button'), - chart: __Highcharts.ChartObject; + chart: Highcharts.ChartObject; $button.click(function () { if (!isLoading) { @@ -932,7 +932,7 @@ function test_Loading() { } function test_Navigation() { - var allDefaults: __Highcharts.NavigationOptions = {}; + var allDefaults: Highcharts.NavigationOptions = {}; // examples $('#container').highcharts({ @@ -974,7 +974,7 @@ function test_Navigation() { } function test_NoData() { - var allDefaults: __Highcharts.NoDataOptions = {}; + var allDefaults: Highcharts.NoDataOptions = {}; // example $('#container').highcharts({ @@ -1000,7 +1000,7 @@ function test_NoData() { } function test_AreaOptions() { - var allDefaults: __Highcharts.AreaChartSeriesOptions = {}; + var allDefaults: Highcharts.AreaChartSeriesOptions = {}; // examples $('#container').highcharts({ @@ -1011,12 +1011,12 @@ function test_AreaOptions() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: <__Highcharts.AreaChartSeriesOptions> { + series: { fillColor: { linearGradient: [0, 0, 0, 300], stops: [ [0, Highcharts.getOptions().colors[0]], - [1, (<__Highcharts.Gradient>Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] + [1, (Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] ] }, fillOpacity: 0.1, @@ -1036,7 +1036,7 @@ function test_AreaOptions() { } function test_AreaRange() { - var allDefaults: __Highcharts.AreaRangeChartSeriesOptions = {}; + var allDefaults: Highcharts.AreaRangeChartSeriesOptions = {}; // example $('#container').highcharts({ @@ -1044,7 +1044,7 @@ function test_AreaRange() { type: "arearange", zoomType: 'x' }, - series: [<__Highcharts.AreaRangeChartSeriesOptions>{ + series: [{ data: (function (arr: number[], len: number) { var i: number; for (i = 0; i < len; i = i + 1) { @@ -1090,7 +1090,7 @@ function test_AreaRange() { legend: { enabled: false }, - series: [<__Highcharts.AreaRangeChartSeriesOptions> { + series: [ { name: 'Temperatures', data: data, dataLabels: { @@ -1105,7 +1105,7 @@ function test_AreaRange() { } function test_Bar() { - var allDefaults: __Highcharts.BarChartSeriesOptions = {}; + var allDefaults: Highcharts.BarChartSeriesOptions = {}; $('#container').highcharts({ chart: { @@ -1115,7 +1115,7 @@ function test_Bar() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: <__Highcharts.BarChartSeriesOptions> { + series: { borderColor: '#303030', borderRadius: 5, borderWidth: 2, @@ -1174,7 +1174,7 @@ function test_Bar() { // grouping example Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color: string) { - return (<__Highcharts.Gradient>Highcharts.Color(color)) + return (Highcharts.Color(color)) .setOpacity(0.5) .get('rgba'); }); @@ -1209,19 +1209,19 @@ function test_Bar() { shadow: false } }, - series: [<__Highcharts.BarChartSeriesOptions> { + series: [ { name: 'Tokyo', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], pointPadding: 0 - }, <__Highcharts.BarChartSeriesOptions> { + }, { name: 'New York', data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3], pointPadding: 0.1 - }, <__Highcharts.BarChartSeriesOptions> { + }, { name: 'London', data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2], pointPadding: 0.2 - }, <__Highcharts.BarChartSeriesOptions> { + }, { name: 'Berlin', data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1], pointPadding: 0.3 @@ -1230,7 +1230,7 @@ function test_Bar() { } function test_BoxPlot() { - var allDefaults: __Highcharts.BoxPlotChartSeriesOptions = {}; + var allDefaults: Highcharts.BoxPlotChartSeriesOptions = {}; // boxplot example $('#container').highcharts({ @@ -1282,7 +1282,7 @@ function test_BoxPlot() { } function test_Bubble() { - var allDefaults: __Highcharts.BubbleChartSeriesOptions = {}; + var allDefaults: Highcharts.BubbleChartSeriesOptions = {}; // bubble example $('#container').highcharts({ @@ -1307,7 +1307,7 @@ function test_Bubble() { maxSize: 50 } }, - series: [<__Highcharts.BubbleChartSeriesOptions> { + series: [ { data: [ [9, 81, 13], [98, 5, 39], @@ -1344,7 +1344,7 @@ function test_Bubble() { subtitle: { text: 'Size is computed by absolute value on negative bubbles' }, - series: [<__Highcharts.BubbleChartSeriesOptions>{ + series: [{ data: [ [-5, 0, -5], [-4, 0, -4], @@ -1365,19 +1365,19 @@ function test_Bubble() { } function test_Column() { - var allDefaults: __Highcharts.ColumnChartSeriesOptions = {}; + var allDefaults: Highcharts.ColumnChartSeriesOptions = {}; // same options as bar chart } function test_ColumnRange() { - var allDefaults: __Highcharts.ColumnRangeChartSeriesOptions = {}; + var allDefaults: Highcharts.ColumnRangeChartSeriesOptions = {}; // same options as bar chart and datalabels from arearange } function test_ErrorBar() { - var allDefaults: __Highcharts.ErrorBarChartSeriesOptions = {}; + var allDefaults: Highcharts.ErrorBarChartSeriesOptions = {}; // error bar styling example $('#container').highcharts({ @@ -1401,7 +1401,7 @@ function test_ErrorBar() { tooltip: { shared: true }, - series: [<__Highcharts.SplineChartSeriesOptions>{ + series: [{ name: 'Temperature', type: 'spline', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], @@ -1411,7 +1411,7 @@ function test_ErrorBar() { tooltip: { pointFormat: '{series.name}: {point.y:.1f}°C
' } - }, <__Highcharts.ErrorBarChartSeriesOptions> { + }, { color: '#FF0000', name: 'Temperature error', type: 'errorbar', @@ -1428,7 +1428,7 @@ function test_ErrorBar() { } function test_Funnel() { - var allDefaults: __Highcharts.FunnelChartSeriesOptions = {}; + var allDefaults: Highcharts.FunnelChartSeriesOptions = {}; // funnel demo $('#container').highcharts({ @@ -1441,7 +1441,7 @@ function test_Funnel() { x: -50 }, plotOptions: { - series: <__Highcharts.FunnelChartSeriesOptions> { + series: { dataLabels: { enabled: true, format: '{point.name} ({point.y:,.0f})', @@ -1472,7 +1472,7 @@ function test_Funnel() { } function test_Gauge() { - var allDefaults: __Highcharts.GaugeChartSeriesOptions = {}; + var allDefaults: Highcharts.GaugeChartSeriesOptions = {}; // example $('#container').highcharts({ @@ -1518,7 +1518,7 @@ function test_Gauge() { } } }, - series: [<__Highcharts.GaugeChartSeriesOptions> { + series: [ { data: [80], overshoot: 5 }] @@ -1526,7 +1526,7 @@ function test_Gauge() { } function test_HeatMap() { - var allDefaults: __Highcharts.HeatMapSeriesOptions = {}; + var allDefaults: Highcharts.HeatMapSeriesOptions = {}; // heatmap demo $('#container').highcharts({ @@ -1574,7 +1574,7 @@ function test_HeatMap() { ], min: -5 }, - series: [<__Highcharts.HeatMapSeriesOptions> { + series: [ { borderWidth: 0, colsize: 24 * 36e5, // one day tooltip: { @@ -1586,7 +1586,7 @@ function test_HeatMap() { } function test_Line() { - var allDefaults: __Highcharts.LineChartSeriesOptions = {}; + var allDefaults: Highcharts.LineChartSeriesOptions = {}; // step example $('#container').highcharts({ @@ -1596,17 +1596,17 @@ function test_Line() { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, - series: [<__Highcharts.LineChartSeriesOptions>{ + series: [{ data: [1, 2, 3, 4, null, 6, 7, null, 9], step: 'right', name: 'Right', linecap: 'round' - }, <__Highcharts.LineChartSeriesOptions>{ + }, { data: [5, 6, 7, 8, null, 10, 11, null, 13], step: 'center', name: 'Center', linecap: 'round' - }, <__Highcharts.LineChartSeriesOptions>{ + }, { data: [9, 10, 11, 12, null, 14, 15, null, 17], step: 'left', name: 'Left', @@ -1616,7 +1616,7 @@ function test_Line() { } function test_Pie() { - var allDefaults: __Highcharts.PieChartSeriesOptions = {}; + var allDefaults: Highcharts.PieChartSeriesOptions = {}; // pie demo $('#container').highcharts({ @@ -1646,7 +1646,7 @@ function test_Pie() { } } }, - series: [<__Highcharts.PieChartSeriesOptions>{ + series: [{ name: "Brands", colorByPoint: true, data: [{ @@ -1705,7 +1705,7 @@ function test_Pie() { center: ['50%', '75%'] } }, - series: [<__Highcharts.PieChartSeriesOptions>{ + series: [{ type: 'pie', name: 'Browser share', innerSize: '50%', @@ -1757,7 +1757,7 @@ function test_Pie() { } function test_Polygon() { - var allDefaults: __Highcharts.PolygonChartSeriesOptions = {}; + var allDefaults: Highcharts.PolygonChartSeriesOptions = {}; $('#container').highcharts({ chart: { @@ -1786,7 +1786,7 @@ function test_Polygon() { } function test_Pyramid() { - var allDefaults: __Highcharts.PyramidChartSeriesOptions = {}; + var allDefaults: Highcharts.PyramidChartSeriesOptions = {}; // pyramid demo $('#container').highcharts({ @@ -1825,10 +1825,10 @@ function test_Pyramid() { } function test_SolidGauge() { - var allDefaults: __Highcharts.SolidGaugeChartSeriesOptions = {}; + var allDefaults: Highcharts.SolidGaugeChartSeriesOptions = {}; // partial solid gauge demo - var gaugeOptions: __Highcharts.Options = { + var gaugeOptions: Highcharts.Options = { chart: { type: 'solidgauge' }, @@ -1880,10 +1880,10 @@ function test_SolidGauge() { } function test_TreeMap() { - var allDefaults: __Highcharts.TreeMapChartSeriesOptions = {}; + var allDefaults: Highcharts.TreeMapChartSeriesOptions = {}; // allowDrillToNode - var treeMap: __Highcharts.TreeMapChartSeriesOptions = { + var treeMap: Highcharts.TreeMapChartSeriesOptions = { type: "treemap", layoutAlgorithm: 'squarified', allowDrillToNode: true, @@ -1932,10 +1932,10 @@ function test_TreeMap() { } function test_Waterfall() { - var allDefaults: __Highcharts.WaterFallChartSeriesOptions = {}; + var allDefaults: Highcharts.WaterFallChartSeriesOptions = {}; // partial waterfall demo - var series: __Highcharts.WaterFallChartSeriesOptions = { + var series: Highcharts.WaterFallChartSeriesOptions = { upColor: Highcharts.getOptions().colors[2], color: Highcharts.getOptions().colors[3], data: [{ @@ -1978,9 +1978,9 @@ function test_Waterfall() { } function test_AxisOptions() { - var allDefaults: __Highcharts.AxisOptions = {}; + var allDefaults: Highcharts.AxisOptions = {}; - var axis: __Highcharts.AxisOptions = { + var axis: Highcharts.AxisOptions = { allowDecimals: false, alternateGridColor: '#000000', breaks: [{ @@ -2168,31 +2168,31 @@ function test_AxisObject() { axis.toPixels(10, true); axis.toValue(10); axis.toValue(10, true); - axis.update(<__Highcharts.AxisOptions>{}); - axis.update(<__Highcharts.AxisOptions>{}, true); + axis.update({}); + axis.update({}, true); } function test_ChartObject() { var chart = $("#container").highcharts(); - chart.addAxis(<__Highcharts.AxisOptions>{}); - chart.addAxis(<__Highcharts.AxisOptions>{}, true); - chart.addAxis(<__Highcharts.AxisOptions>{}, true, false); - chart.addAxis(<__Highcharts.AxisOptions>{}, true, true, false); - chart.addAxis(<__Highcharts.AxisOptions>{}, true, true, {duration: 50}); - chart.addSeries(<__Highcharts.IndividualSeriesOptions>{}); - chart.addSeries(<__Highcharts.IndividualSeriesOptions>{}, false); - chart.addSeries(<__Highcharts.IndividualSeriesOptions>{}, false, false); - chart.addSeries(<__Highcharts.IndividualSeriesOptions>{}, false, {duration: 50}); - chart.addSeriesAsDrilldown(<__Highcharts.PointObject>{}, <__Highcharts.IndividualSeriesOptions>{}); + chart.addAxis({}); + chart.addAxis({}, true); + chart.addAxis({}, true, false); + chart.addAxis({}, true, true, false); + chart.addAxis({}, true, true, {duration: 50}); + chart.addSeries({}); + chart.addSeries({}, false); + chart.addSeries({}, false, false); + chart.addSeries({}, false, {duration: 50}); + chart.addSeriesAsDrilldown({}, {}); var container = chart.container; console.log(container.id); chart.destroy(); chart.drillUp(); - chart.exportChart(<__Highcharts.ExportingOptions>{}, <__Highcharts.Options>{}); - chart.exportChartLocal(<__Highcharts.ExportingOptions>{}, <__Highcharts.Options>{}); + chart.exportChart({}, {}); + chart.exportChartLocal({}, {}); var object = chart.get('axisIdOrSeriesIdOrPointId'); var svg1 = chart.getSVG(); - var svg2 = chart.getSVG(<__Highcharts.Options>{}); + var svg2 = chart.getSVG({}); var selectedPoints = chart.getSelectedPoints(); var selectedSeries = chart.getSelectedSeries(); chart.hideLoading(); @@ -2257,7 +2257,7 @@ function test_ElementObject() { } function test_PointObject() { - var point = <__Highcharts.PointObject>$('#container').highcharts().get('point1'); + var point = $('#container').highcharts().get('point1'); var category = point.category; var percentage = point.percentage; point.index; @@ -2298,7 +2298,7 @@ function test_RendererObject() { } function test_SeriesObject() { - var series = <__Highcharts.SeriesObject>$('#container').highcharts().get('series1'); + var series = $('#container').highcharts().get('series1'); series.addPoint(0); series.addPoint([0, 0]); series.addPoint({}); diff --git a/highcharts/highstock-tests.ts b/highcharts/highstock-tests.ts index fda21c1616..ac7cb883f2 100644 --- a/highcharts/highstock-tests.ts +++ b/highcharts/highstock-tests.ts @@ -1,5 +1,5 @@ - /// +import * as Highcharts from "highcharts"; var someData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; @@ -55,7 +55,7 @@ $(function () { } }, - series: [<__Highcharts.AreaRangeChartSeriesOptions>{ + series: [{ name: 'USD to EUR', data: someData, lineColor: "blue" diff --git a/highcharts/highstock.d.ts b/highcharts/highstock.d.ts index bf57b32429..f312286745 100644 --- a/highcharts/highstock.d.ts +++ b/highcharts/highstock.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace __Highstock { - interface ChartObject extends __Highcharts.ChartObject { + interface ChartObject extends Highcharts.ChartObject { options: Options; } @@ -22,9 +22,9 @@ declare namespace __Highstock { maskInside?: boolean; outlineColor?: string; outlineWidth?: number; - series?: __Highcharts.IndividualSeriesOptions; - xAxis?: __Highcharts.AxisOptions; - yAxis?: __Highcharts.AxisOptions; + series?: Highcharts.IndividualSeriesOptions; + xAxis?: Highcharts.AxisOptions; + yAxis?: Highcharts.AxisOptions; } interface RangeSelectorButton { @@ -53,8 +53,8 @@ declare namespace __Highstock { x?: number; y?: number; }; - inputStyle?: __Highcharts.CSSObject; - labelStyle?: __Highcharts.CSSObject; + inputStyle?: Highcharts.CSSObject; + labelStyle?: Highcharts.CSSObject; selected?: number; } @@ -79,7 +79,7 @@ declare namespace __Highstock { trackBorderWidth?: number; } - interface Options extends __Highcharts.Options { + interface Options extends Highcharts.Options { navigator?: NavigatorOptions; rangeSelector?: RangeSelectorOptions; scrollbar?: ScrollbarOptions; @@ -90,7 +90,7 @@ declare namespace __Highstock { new (options: Options, callback: (chart: ChartObject) => void): ChartObject; } - interface Static extends __Highcharts.Static { + interface Static extends Highcharts.Static { StockChart: Chart; } } @@ -101,21 +101,21 @@ interface JQuery { /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') - * @param {__Highcharts.Options} options Options for this chart + * @param {Highcharts.Options} options Options for this chart * @return current {JQuery} selector the current JQuery selector **/ highcharts(type: "StockChart", options: __Highstock.Options): JQuery; /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') - * @param {__Highcharts.Options} options Options for this chart + * @param {Highcharts.Options} options Options for this chart * @param callback Callback function used to manipulate the constructed chart instance * @return current {JQuery} selector the current JQuery selector **/ highcharts(type: "StockChart", options: __Highstock.Options, callback: (chart: __Highstock.ChartObject) => void): JQuery; - highcharts(type: string): __Highcharts.ChartObject; - highcharts(type: string, options: __Highcharts.Options): JQuery; - highcharts(type: string, options: __Highcharts.Options, callback: (chart: __Highcharts.ChartObject) => void): JQuery; + highcharts(type: string): Highcharts.ChartObject; + highcharts(type: string, options: Highcharts.Options): JQuery; + highcharts(type: string, options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; } diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 7f2d28e99b..7114d1a646 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Damiano Gambarotto , Dan Lewi Harkestad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace __Highcharts { +declare namespace Highcharts { interface Position { align?: string; verticalAlign?: string; @@ -2244,7 +2244,7 @@ declare namespace __Highcharts { formAttributes?: any; /** * Path where Highcharts will look for export module dependencies to load on demand if they don't already exist on - * window. Should currently point to location of CanVG library (https://github.com/canvg/canvg) and RGBColor.js, + * window. Should currently point to location of CanVG library (https://github.com/canvg/canvg) and RGBColor.js, * required for client side export in certain browsers. * @default 'http://code.highcharts.com/{version}/lib' * @since 5.0.0 @@ -2989,7 +2989,7 @@ declare namespace __Highcharts { */ padding?: number; /** - * Whether to reserve space for the labels. This can be turned off when for example the labels are rendered inside + * Whether to reserve space for the labels. This can be turned off when for example the labels are rendered inside * the plot area instead of outside. * @default true * @since 4.1.10 @@ -4952,8 +4952,8 @@ declare namespace __Highcharts { } /* You will rarely, if ever, want to use this interface directly. Instead it is much more useful to use one of the derived - * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) - */ + * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) + */ interface IndividualSeriesOptions { type?: string; /** @@ -6445,33 +6445,28 @@ declare namespace __Highcharts { } } -interface JQuery { - highcharts(): __Highcharts.ChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {Options} options Options for this chart - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(options: __Highcharts.Options): JQuery; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {Options} options Options for this chart - * @param callback Callback function used to manipulate the constructed chart instance - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(options: __Highcharts.Options, callback: (chart: __Highcharts.ChartObject) => void): JQuery; +declare global { + interface JQuery { + highcharts(): Highcharts.ChartObject; + /** + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Options} options Options for this chart + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(options: Highcharts.Options): JQuery; + /** + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Options} options Options for this chart + * @param callback Callback function used to manipulate the constructed chart instance + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + } + + var Highcharts: Highcharts.Static; } -/** - * Enabling the usage of ES6 module loading. - */ -declare var Highcharts: __Highcharts.Static; - -/** - * Declaration for ES6 module loading. - */ -declare module "highcharts" { - export = __Highcharts; -} +export = Highcharts; +export as namespace Highcharts; diff --git a/highcharts/tsconfig.json b/highcharts/tsconfig.json index 735490820e..ac1cda76a2 100644 --- a/highcharts/tsconfig.json +++ b/highcharts/tsconfig.json @@ -16,6 +16,7 @@ "index.d.ts", "highstock.d.ts", "highcharts-tests.ts", + "highcharts-modules-no-data-to-display-tests.ts", "highstock-tests.ts" ] } \ No newline at end of file From 832d3c938aba5c802018e9786ff99d1e03fd6ae6 Mon Sep 17 00:00:00 2001 From: krauseStefan Date: Wed, 2 Nov 2016 18:02:45 +0100 Subject: [PATCH 044/131] types(selenium): fix typings error Level class in logging namespace The 'name' and 'value' properties should not be defined as function, they are inplemented using es6 get functions get value() { return this.value_; } see https://github.com/SeleniumHQ/selenium/blob/ba56ad1ae0b98a1fe1efdd2163c62fc847950178/javascript/node/selenium-webdriver/lib/logging.js#L95 --- selenium-webdriver/index.d.ts | 4 ++-- selenium-webdriver/selenium-webdriver-tests.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 97722de9b6..bda0820ab5 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1777,10 +1777,10 @@ declare namespace webdriver { toString(): string; /** This logger's name. */ - name(): string; + name: string; /** The numeric log level. */ - value(): number; + value: number; /** * Indicates no log messages should be recorded. diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4e3aa348a3..fa0b0a386e 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -849,8 +849,8 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name(); - var value: number = level.value(); + var name: string = level.name; + var value: number = level.value; var type: string; type = webdriver.logging.Type.BROWSER; From d9a737331c85b4dfc50436083efc7e026da26d96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Podeszwa?= Date: Wed, 2 Nov 2016 19:12:39 +0100 Subject: [PATCH 045/131] Change StackPolicyBody and StackPolicyUrl to accept string instead of array of strings --- aws-sdk/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index 7d70edf939..01615fc4cd 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -616,8 +616,8 @@ export module CloudFormation { ResourceTypes?: string[]; OnFailure?: string[]; // cannot specify both DisableRollback and OnFailure // DO_NOTHING | ROLLBACK | DELETE - StackPolicyBody?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL - StackPolicyURL?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL + StackPolicyBody?: string; // cannot specify both StackPolicyBody and StackPolicyURL + StackPolicyURL?: string; // cannot specify both StackPolicyBody and StackPolicyURL Tags?: CloudFormation.Tag[]; } From b6e41e21ff66f0118225e35656f50d931b4678be Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 2 Nov 2016 12:48:30 -0700 Subject: [PATCH 046/131] Fix `declare var Highcharts`: do it in module scope, not in global scope (that's what `export as namespace` is for) --- highcharts/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 7114d1a646..4c71b46e73 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -6464,9 +6464,8 @@ declare global { **/ highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; } - - var Highcharts: Highcharts.Static; } +declare var Highcharts: Highcharts.Static; export = Highcharts; export as namespace Highcharts; From 1907cc359bba46fb875f3c19226bdf30d49d37a3 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 2 Nov 2016 13:10:12 -0700 Subject: [PATCH 047/131] Convert `highcharts-modules-xxx.d.ts` to `highcharts/modules/xxx.d.ts` and include in tsconfig.json --- highcharts/highcharts-more-tests.ts | 1 + highcharts/highcharts-more.d.ts | 10 +++------- highcharts/modules/boost-tests.ts | 1 + .../boost.d.ts} | 6 ++---- highcharts/modules/exporting-tests.ts | 1 + .../exporting.d.ts} | 6 ++---- .../no-data-to-display-tests.ts} | 3 --- .../no-data-to-display.d.ts} | 0 highcharts/modules/offline-exporting-tests.ts | 1 + .../offline-exporting.d.ts} | 6 ++---- highcharts/tsconfig.json | 13 +++++++++++-- 11 files changed, 24 insertions(+), 24 deletions(-) create mode 100644 highcharts/highcharts-more-tests.ts create mode 100644 highcharts/modules/boost-tests.ts rename highcharts/{highcharts-modules-boost.d.ts => modules/boost.d.ts} (80%) create mode 100644 highcharts/modules/exporting-tests.ts rename highcharts/{highcharts-modules-exporting.d.ts => modules/exporting.d.ts} (79%) rename highcharts/{highcharts-modules-no-data-to-display-tests.ts => modules/no-data-to-display-tests.ts} (65%) rename highcharts/{highcharts-modules-no-data-to-display.d.ts => modules/no-data-to-display.d.ts} (100%) create mode 100644 highcharts/modules/offline-exporting-tests.ts rename highcharts/{highcharts-modules-offline-exporting.d.ts => modules/offline-exporting.d.ts} (77%) diff --git a/highcharts/highcharts-more-tests.ts b/highcharts/highcharts-more-tests.ts new file mode 100644 index 0000000000..e6e5e9af5c --- /dev/null +++ b/highcharts/highcharts-more-tests.ts @@ -0,0 +1 @@ +HighchartsMore(Highcharts); diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts index b93b286563..dd5950fe35 100644 --- a/highcharts/highcharts-more.d.ts +++ b/highcharts/highcharts-more.d.ts @@ -3,10 +3,6 @@ // Definitions by: Maciej Suchecki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Static } from "highcharts"; - -declare var HighchartsMore: (H: Static) => Static; - -declare module "highcharts/highcharts-more" { - export = HighchartsMore; -} +declare var HighchartsMore: (H: Highcharts.Static) => Highcharts.Static; +export = HighchartsMore; +export as namespace HighchartsMore; diff --git a/highcharts/modules/boost-tests.ts b/highcharts/modules/boost-tests.ts new file mode 100644 index 0000000000..98202a2129 --- /dev/null +++ b/highcharts/modules/boost-tests.ts @@ -0,0 +1 @@ +HighchartsBoost(Highcharts); diff --git a/highcharts/highcharts-modules-boost.d.ts b/highcharts/modules/boost.d.ts similarity index 80% rename from highcharts/highcharts-modules-boost.d.ts rename to highcharts/modules/boost.d.ts index 5670df007b..9b62dab1c7 100644 --- a/highcharts/highcharts-modules-boost.d.ts +++ b/highcharts/modules/boost.d.ts @@ -6,7 +6,5 @@ import { Static } from "highcharts"; declare var HighchartsBoost: (H: Static) => Static; - -declare module "highcharts/modules/boost" { - export = HighchartsBoost; -} +export = HighchartsBoost; +export as namespace HighchartsBoost; diff --git a/highcharts/modules/exporting-tests.ts b/highcharts/modules/exporting-tests.ts new file mode 100644 index 0000000000..22bced1b24 --- /dev/null +++ b/highcharts/modules/exporting-tests.ts @@ -0,0 +1 @@ +HighchartsExporting(Highcharts); diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/modules/exporting.d.ts similarity index 79% rename from highcharts/highcharts-modules-exporting.d.ts rename to highcharts/modules/exporting.d.ts index 207e50ab8e..877ef3d0c1 100644 --- a/highcharts/highcharts-modules-exporting.d.ts +++ b/highcharts/modules/exporting.d.ts @@ -6,7 +6,5 @@ import { Static } from "highcharts"; declare var HighchartsExporting: (H: Static) => Static; - -declare module "highcharts/modules/exporting" { - export = HighchartsExporting; -} +export = HighchartsExporting; +export as namespace HighchartsExporting; diff --git a/highcharts/highcharts-modules-no-data-to-display-tests.ts b/highcharts/modules/no-data-to-display-tests.ts similarity index 65% rename from highcharts/highcharts-modules-no-data-to-display-tests.ts rename to highcharts/modules/no-data-to-display-tests.ts index acd06d2f9f..84392c3bf4 100644 --- a/highcharts/highcharts-modules-no-data-to-display-tests.ts +++ b/highcharts/modules/no-data-to-display-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function test_NoDataToDisplay() { var chart = $("#container").highcharts(); var chartHasData = chart.hasData(); diff --git a/highcharts/highcharts-modules-no-data-to-display.d.ts b/highcharts/modules/no-data-to-display.d.ts similarity index 100% rename from highcharts/highcharts-modules-no-data-to-display.d.ts rename to highcharts/modules/no-data-to-display.d.ts diff --git a/highcharts/modules/offline-exporting-tests.ts b/highcharts/modules/offline-exporting-tests.ts new file mode 100644 index 0000000000..22bced1b24 --- /dev/null +++ b/highcharts/modules/offline-exporting-tests.ts @@ -0,0 +1 @@ +HighchartsExporting(Highcharts); diff --git a/highcharts/highcharts-modules-offline-exporting.d.ts b/highcharts/modules/offline-exporting.d.ts similarity index 77% rename from highcharts/highcharts-modules-offline-exporting.d.ts rename to highcharts/modules/offline-exporting.d.ts index ff4de198ea..94ecf53485 100644 --- a/highcharts/highcharts-modules-offline-exporting.d.ts +++ b/highcharts/modules/offline-exporting.d.ts @@ -6,7 +6,5 @@ import { Static } from "highcharts"; declare var HighchartsOfflineExporting: (H: Static) => Static; - -declare module "highcharts/modules/offline-exporting" { - export = HighchartsOfflineExporting; -} +export = HighchartsOfflineExporting; +export as namespace HighchartsOfflineExporting; diff --git a/highcharts/tsconfig.json b/highcharts/tsconfig.json index ac1cda76a2..8082640c3b 100644 --- a/highcharts/tsconfig.json +++ b/highcharts/tsconfig.json @@ -14,9 +14,18 @@ }, "files": [ "index.d.ts", - "highstock.d.ts", "highcharts-tests.ts", - "highcharts-modules-no-data-to-display-tests.ts", + "modules/boost.d.ts", + "modules/boost-tests.ts", + "modules/exporting.d.ts", + "modules/exporting-tests.ts", + "modules/no-data-to-display.d.ts", + "modules/no-data-to-display-tests.ts", + "modules/offline-exporting.d.ts", + "modules/offline-exporting-tests.ts", + "highcharts-more.d.ts", + "highcharts-more-tests.ts", + "highstock.d.ts", "highstock-tests.ts" ] } \ No newline at end of file From 562df78122170427d13d842f9c0d358b5cf88cb3 Mon Sep 17 00:00:00 2001 From: Borek Bernard Date: Thu, 3 Nov 2016 01:04:34 +0100 Subject: [PATCH 048/131] Fix return type of `config()`, add documentation (#12347) * Fixed return type of `config()`, doc comments added * Returned the original author name --- dotenv/dotenv-tests.ts | 14 +++++++++----- dotenv/index.d.ts | 31 +++++++++++++++++++++++++++---- dotenv/tsconfig.json | 4 ++-- 3 files changed, 38 insertions(+), 11 deletions(-) diff --git a/dotenv/dotenv-tests.ts b/dotenv/dotenv-tests.ts index ea54a99b6d..3d9af0f52e 100644 --- a/dotenv/dotenv-tests.ts +++ b/dotenv/dotenv-tests.ts @@ -1,15 +1,19 @@ - - import dotenv = require('dotenv'); -dotenv.config({ +// typically, result will be an Object +let env = dotenv.config({ silent: true }); +// ... but it might also be `false` +let result = dotenv.config({ + path: '.non-existing-env' +}); + dotenv.config({ path: '.env' -}) +}); dotenv.config({ encoding: 'utf8' -}) \ No newline at end of file +}); diff --git a/dotenv/index.d.ts b/dotenv/index.d.ts index 7391133781..a326ceaa58 100644 --- a/dotenv/index.d.ts +++ b/dotenv/index.d.ts @@ -1,12 +1,35 @@ // Type definitions for dotenv 2.0.0 // Project: https://github.com/motdotla/dotenv -// Definitions by: Jussi Kinnula -// Definitions: https://github.com/jussikinnula/DefinitelyTyped +// Definitions by: Jussi Kinnula , Borek Bernard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function config(options?: dotenvOptions): boolean; +/** + * Loads `.env` into `process.env`. + * + * @param options + * @return Object Object with the parsed keys and values, e.g., 'KEY=value' becomes { KEY: 'value' } + */ +export function config(options?: DotenvOptions): Object | false; -interface dotenvOptions { +export interface DotenvOptions { + /** + * Dotenv outputs a warning to your console if missing a .env file. Suppress this warning using silent. + * + * @default false + */ silent?: boolean; + + /** + * You can specify a custom path if your file containing environment variables is named or located differently. + * + * @default '.env' + */ path?: string; + + /** + * You may specify the encoding of your file containing environment variables using this option. + * + * @default 'utf8' + */ encoding?: string; } diff --git a/dotenv/tsconfig.json b/dotenv/tsconfig.json index bbd1c438e6..fcecbfabaf 100644 --- a/dotenv/tsconfig.json +++ b/dotenv/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -16,4 +16,4 @@ "index.d.ts", "dotenv-tests.ts" ] -} \ No newline at end of file +} From c73c01f3f6e50f49be54153013e878cb6f71e1d2 Mon Sep 17 00:00:00 2001 From: Rand Scullard Date: Wed, 2 Nov 2016 20:04:47 -0400 Subject: [PATCH 049/131] passport: Added generic versions of serializeUser and deserializeUser for strong typing. (#12446) --- passport/index.d.ts | 2 ++ passport/passport-tests.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/passport/index.d.ts b/passport/index.d.ts index b8533cadea..629f78344c 100644 --- a/passport/index.d.ts +++ b/passport/index.d.ts @@ -45,7 +45,9 @@ declare module 'passport' { authorize(strategies: string[], callback?: Function): express.Handler; authorize(strategies: string[], options: Object, callback?: Function): express.Handler; serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; + serializeUser(fn: (user: TUser, done: (err: any, id: TID) => void) => void): void; deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; + deserializeUser(fn: (id: TID, done: (err: any, user: TUser) => void) => void): void; transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; } diff --git a/passport/passport-tests.ts b/passport/passport-tests.ts index 2535bb80ca..06fd9cd692 100644 --- a/passport/passport-tests.ts +++ b/passport/passport-tests.ts @@ -29,7 +29,9 @@ const newFramework:passport.Framework = { passport.use(new TestStrategy()); passport.framework(newFramework); passport.serializeUser((user, done) => { }); +passport.serializeUser((user, done) => { }); passport.deserializeUser((id, done) => { }); +passport.deserializeUser((id, done) => { }); passport.use(new TestStrategy()) .unuse('test') From 6d0b399f51eb8837f8ad2c4b1e040690f7adef47 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 2 Nov 2016 18:54:15 -0700 Subject: [PATCH 050/131] Fix for https://github.com/Microsoft/TypeScript/issues/11916 (#12425) * Switch express-serve-static-core to a module * Add tsconfig to aws-serverless-express * Switch aws-serverless-express to module * Fix dangling pointer * Fix wrong file name * Add tsconfig.json * switch seamless-immutable a module * Add tsconfig.json * use --strictNullChecks --- .../aws-serverless-express-tests.ts | 3 +- .../aws-serverless-express.d.ts | 24 - aws-serverless-express/index.d.ts | 19 + aws-serverless-express/tsconfig.json | 19 + express-serve-static-core/index.d.ts | 2192 ++++++++--------- qunit/{qunit-test.ts => qunit-tests.ts} | 114 +- .../{seamless-immutable.d.ts => index.d.ts} | 8 +- .../seamless-immutable-tests.ts | 1 - seamless-immutable/tsconfig.json | 19 + uritemplate/{uritemplate.d.ts => index.d.ts} | 0 uritemplate/tsconfig.json | 19 + uritemplate/uritemplate-tests.ts | 3 +- 12 files changed, 1233 insertions(+), 1188 deletions(-) delete mode 100644 aws-serverless-express/aws-serverless-express.d.ts create mode 100644 aws-serverless-express/index.d.ts create mode 100644 aws-serverless-express/tsconfig.json rename qunit/{qunit-test.ts => qunit-tests.ts} (98%) rename seamless-immutable/{seamless-immutable.d.ts => index.d.ts} (97%) create mode 100644 seamless-immutable/tsconfig.json rename uritemplate/{uritemplate.d.ts => index.d.ts} (100%) create mode 100644 uritemplate/tsconfig.json diff --git a/aws-serverless-express/aws-serverless-express-tests.ts b/aws-serverless-express/aws-serverless-express-tests.ts index 6a0d7694d9..c46056ed25 100644 --- a/aws-serverless-express/aws-serverless-express-tests.ts +++ b/aws-serverless-express/aws-serverless-express-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// import * as awsServerlessExpress from 'aws-serverless-express'; import * as express from 'express'; diff --git a/aws-serverless-express/aws-serverless-express.d.ts b/aws-serverless-express/aws-serverless-express.d.ts deleted file mode 100644 index 50aa0e1a0b..0000000000 --- a/aws-serverless-express/aws-serverless-express.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Type definitions for aws-serverless-express -// Project: https://github.com/awslabs/aws-serverless-express -// Definitions by: Ben Speakman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module 'aws-serverless-express' { - - import * as http from 'http'; - import * as lambda from 'aws-lambda'; - - export function createServer( - requestListener: (request: http.IncomingMessage, response: http.ServerResponse) => http.Server, - serverListenCallback?: () => any - ): http.Server; - - export function proxy( - server: http.Server, - event: any, - context: lambda.Context - ): void; -} diff --git a/aws-serverless-express/index.d.ts b/aws-serverless-express/index.d.ts new file mode 100644 index 0000000000..e4601e6ccd --- /dev/null +++ b/aws-serverless-express/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for aws-serverless-express +// Project: https://github.com/awslabs/aws-serverless-express +// Definitions by: Ben Speakman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as http from 'http'; +import * as lambda from 'aws-lambda'; + +export function createServer( + requestListener: (request: http.IncomingMessage, response: http.ServerResponse) => http.Server, + serverListenCallback?: () => any +): http.Server; + +export function proxy( + server: http.Server, + event: any, + context: lambda.Context +): void; \ No newline at end of file diff --git a/aws-serverless-express/tsconfig.json b/aws-serverless-express/tsconfig.json new file mode 100644 index 0000000000..7b42b1f538 --- /dev/null +++ b/aws-serverless-express/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws-serverless-express-tests.ts" + ] +} \ No newline at end of file diff --git a/express-serve-static-core/index.d.ts b/express-serve-static-core/index.d.ts index 92f27d5df8..932b8075b1 100644 --- a/express-serve-static-core/index.d.ts +++ b/express-serve-static-core/index.d.ts @@ -5,1101 +5,1101 @@ // This extracts the core definitions from express to prevent a circular dependency between express and serve-static /// -declare namespace Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - -declare module "express-serve-static-core" { - import * as http from "http"; - - interface NextFunction { - (err?: any): void; - } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - type PathParams = string | RegExp | (string | RegExp)[]; - - type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; - - interface IRouterMatcher { - (path: PathParams, ...handlers: RequestHandler[]): T; - (path: PathParams, ...handlers: RequestHandlerParams[]): T; - } - - interface IRouterHandler { - (...handlers: RequestHandler[]): T; - (...handlers: RequestHandlerParams[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - // deprecated since express 4.11.0 - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; - - checkout: IRouterMatcher; - copy: IRouterMatcher; - lock: IRouterMatcher; - merge: IRouterMatcher; - mkactivity: IRouterMatcher; - mkcol: IRouterMatcher; - move: IRouterMatcher; - "m-search": IRouterMatcher; - notify: IRouterMatcher; - purge: IRouterMatcher; - report: IRouterMatcher; - search: IRouterMatcher; - subscribe: IRouterMatcher; - trace: IRouterMatcher; - unlock: IRouterMatcher; - unsubscribe: IRouterMatcher; - - use: IRouterHandler & IRouterMatcher; - - route(prefix: PathParams): IRoute; - /** - * Stack of configured routes - */ - stack: any[]; - } - - interface IRoute { - path: string; - stack: any; - all: IRouterHandler; - get: IRouterHandler; - post: IRouterHandler; - put: IRouterHandler; - delete: IRouterHandler; - patch: IRouterHandler; - options: IRouterHandler; - head: IRouterHandler; - - checkout: IRouterHandler; - copy: IRouterHandler; - lock: IRouterHandler; - merge: IRouterHandler; - mkactivity: IRouterHandler; - mkcol: IRouterHandler; - move: IRouterHandler; - "m-search": IRouterHandler; - notify: IRouterHandler; - purge: IRouterHandler; - report: IRouterHandler; - search: IRouterHandler; - subscribe: IRouterHandler; - trace: IRouterHandler; - unlock: IRouterHandler; - unsubscribe: IRouterHandler - } - - export interface Router extends IRouter { } - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date | boolean; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean | 'auto'; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.IncomingMessage, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get(name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(): string[]; - accepts(type: string): string | boolean; - accepts(type: string[]): string | boolean; - accepts(...type: string[]): string | boolean; - - /** - * Returns the first accepted charset of the specified character sets, - * based on the request's Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ - acceptsCharsets(): string[]; - acceptsCharsets(charset: string): string | boolean; - acceptsCharsets(charset: string[]): string | boolean; - acceptsCharsets(...charset: string[]): string | boolean; - - /** - * Returns the first accepted encoding of the specified encodings, - * based on the request's Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ - acceptsEncodings(): string[]; - acceptsEncodings(encoding: string): string | boolean; - acceptsEncodings(encoding: string[]): string | boolean; - acceptsEncodings(...encoding: string[]): string | boolean; - - /** - * Returns the first accepted language of the specified languages, - * based on the request's Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ - acceptsLanguages(): string[]; - acceptsLanguages(lang: string): string | boolean; - acceptsLanguages(lang: string[]): string | boolean; - acceptsLanguages(...lang: string[]): string | boolean; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * @deprecated Use either req.params, req.body or req.query, as applicable. - * - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - - baseUrl: string; - - app: Application; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body?: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get(field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(view: string, callback?: (err: Error, html: string) => void): void; - - locals: any; - - charset: string; - - /** - * Adds the field to the Vary response header, if it is not there already. - * Examples: - * - * res.vary('User-Agent').render('docs'); - * - */ - vary(field: string): Response; - } - - interface Handler extends RequestHandler { } - - interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, value: any, name: string): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Express instance itself is a request handler, which could be invoked without - * third argument. - */ - (req: Request, res: Response): any; - - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: {(name: string): any;} & IRouterMatcher; - - param(name: string | string[], handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - - /** - * Used to get all registered routes in Express Application - */ - _router: any; - } - - interface Express extends Application { - request: Request; - - response: Response; +declare global { + namespace Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/method-override/method-override.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } } } + +import * as http from "http"; + +interface NextFunction { + (err?: any): void; +} + +interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; +} + +interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; +} + +type PathParams = string | RegExp | (string | RegExp)[]; + +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + +interface IRouterMatcher { + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +} + +interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; +} + +interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + checkout: IRouterMatcher; + copy: IRouterMatcher; + lock: IRouterMatcher; + merge: IRouterMatcher; + mkactivity: IRouterMatcher; + mkcol: IRouterMatcher; + move: IRouterMatcher; + "m-search": IRouterMatcher; + notify: IRouterMatcher; + purge: IRouterMatcher; + report: IRouterMatcher; + search: IRouterMatcher; + subscribe: IRouterMatcher; + trace: IRouterMatcher; + unlock: IRouterMatcher; + unsubscribe: IRouterMatcher; + + use: IRouterHandler & IRouterMatcher; + + route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: any[]; +} + +interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + + checkout: IRouterHandler; + copy: IRouterHandler; + lock: IRouterHandler; + merge: IRouterHandler; + mkactivity: IRouterHandler; + mkcol: IRouterHandler; + move: IRouterHandler; + "m-search": IRouterHandler; + notify: IRouterHandler; + purge: IRouterHandler; + report: IRouterHandler; + search: IRouterHandler; + subscribe: IRouterHandler; + trace: IRouterHandler; + unlock: IRouterHandler; + unsubscribe: IRouterHandler +} + +export interface Router extends IRouter { } + +interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date | boolean; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean | 'auto'; +} + +interface Errback { (err: Error): void; } + +interface Request extends http.IncomingMessage, Express.Request { + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get(name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(): string[]; + accepts(type: string): string | boolean; + accepts(type: string[]): string | boolean; + accepts(...type: string[]): string | boolean; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request's Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param charset + */ + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | boolean; + acceptsCharsets(charset: string[]): string | boolean; + acceptsCharsets(...charset: string[]): string | boolean; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request's Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param encoding + */ + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | boolean; + acceptsEncodings(encoding: string[]): string | boolean; + acceptsEncodings(...encoding: string[]): string | boolean; + + /** + * Returns the first accepted language of the specified languages, + * based on the request's Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * + * @param lang + */ + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | boolean; + acceptsLanguages(lang: string[]): string | boolean; + acceptsLanguages(...lang: string[]): string | boolean; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * @deprecated Use either req.params, req.body or req.query, as applicable. + * + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; +} + +interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; +} + +interface Send { + (status: number, body?: any): Response; + (body?: any): Response; +} + +interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + download(path: string, filename: string): void; + download(path: string, fn: Errback): void; + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): Response; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): Response; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): Response; + set(field: string, value?: string): Response; + + header(field: any): Response; + header(field: string, value?: string): Response; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** + * Get value for header `field`. + * + * @param field + */ + get(field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + cookie(name: string, val: any, options: CookieOptions): Response; + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(view: string, callback?: (err: Error, html: string) => void): void; + + locals: any; + + charset: string; + + /** + * Adds the field to the Vary response header, if it is not there already. + * Examples: + * + * res.vary('User-Agent').render('docs'); + * + */ + vary(field: string): Response; +} + +interface Handler extends RequestHandler { } + +interface RequestParamHandler { + (req: Request, res: Response, next: NextFunction, value: any, name: string): any; +} + +interface Application extends IRouter, Express.Application { + /** + * Express instance itself is a request handler, which could be invoked without + * third argument. + */ + (req: Request, res: Response): any; + + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set(setting: string, val: any): Application; + get: { (name: string): any; } & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(fn: Function): Application; + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + listen(port: number, hostname: string, callback?: Function): http.Server; + listen(port: number, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + + /** + * Used to get all registered routes in Express Application + */ + _router: any; +} + +interface Express extends Application { + request: Request; + + response: Response; +} \ No newline at end of file diff --git a/qunit/qunit-test.ts b/qunit/qunit-tests.ts similarity index 98% rename from qunit/qunit-test.ts rename to qunit/qunit-tests.ts index b5362b4c14..6a739b8213 100644 --- a/qunit/qunit-test.ts +++ b/qunit/qunit-tests.ts @@ -1,5 +1,3 @@ -/// - QUnit.module( "group a" ); QUnit.test( "a basic test example", function( assert ) { @@ -8,7 +6,7 @@ QUnit.test( "a basic test example", function( assert ) { QUnit.test( "a basic test example 2", function( assert ) { assert.ok( true, "this test is fine" ); }); - + QUnit.module( "group b" ); QUnit.test( "a basic test example 3", function( assert ) { assert.ok( true, "this test is fine" ); @@ -23,14 +21,14 @@ QUnit.module( "module a", function() { assert.ok( true, "this test is fine" ); }); }); - + QUnit.module( "module b", function() { QUnit.test( "a basic test example 2", function( assert ) { assert.ok( true, "this test is fine" ); }); - + QUnit.module( "nested module b.1", function() { - + // This test will be prefixed with the following module label: // "module b > nested module b.1" QUnit.test( "a basic test example 3", function( assert ) { @@ -61,13 +59,13 @@ QUnit.module( "Machine Maker", { this.parts = [ "wheels", "motor", "chassis" ]; } }); - + QUnit.test( "makes a robot", function( assert ) { this.parts.push( "arduino" ); assert.equal( this.maker.build( this.parts ), "robot" ); assert.deepEqual( this.maker.made, [ "robot" ] ); }); - + QUnit.test( "makes a car", function( assert ) { assert.equal( this.maker.build( this.parts ), "car" ); this.maker.duplicate(); @@ -75,31 +73,31 @@ QUnit.test( "makes a car", function( assert ) { }); QUnit.module( "grouped tests argument hooks", function( hooks ) { - + hooks.beforeEach( function( assert ) { assert.ok( true, "beforeEach called" ); } ); - + hooks.afterEach( function( assert ) { assert.ok( true, "afterEach called" ); } ); - + QUnit.test( "call hooks", function( assert ) { assert.expect( 2 ); } ); - + QUnit.module( "stacked hooks", function( hooks ) { - + // This will run after the parent module's beforeEach hook hooks.beforeEach( function( assert ) { assert.ok( true, "nested beforeEach called" ); } ); - + // This will run before the parent module's afterEach hooks.afterEach( function( assert ) { assert.ok( true, "nested afterEach called" ); } ); - + QUnit.test( "call hooks", function( assert ) { assert.expect( 4 ); } ); @@ -149,11 +147,11 @@ QUnit.done(function( details ) { }); QUnit.log(function( obj ) { - + // Parse some stuff before sending it. var actual = QUnit.dump.parse( obj.actual ); var expected = QUnit.dump.parse( obj.expected ); - + // Send it. // sendMessage( "qunit.log", obj.result, actual, expected, obj.message, obj.source ); console.log("qunit.log", obj.result, actual, expected, obj.message, obj.source); @@ -161,7 +159,7 @@ QUnit.log(function( obj ) { var qHeader = document.getElementById( "qunit-header" ), parsed = QUnit.dump.parse( qHeader ); - + console.log( parsed ); var input: any = { @@ -173,7 +171,7 @@ var input: any = { QUnit.dump.maxDepth = 1; console.log( QUnit.dump.parse( input ) ); // Logs: { "parts": [object Object] } - + QUnit.dump.maxDepth = 2; console.log( QUnit.dump.parse( input ) ); // Logs: { "parts": { "back": [object Array], "front": [object Array] } } @@ -189,7 +187,7 @@ QUnit.test( "QUnit.extend", function( assert ) { c: 3, z: undefined } ); - + assert.equal( base.a, 1, "Unspecified values are not modified" ); assert.equal( base.b, 2.5, "Existing values are updated" ); assert.equal( base.c, 3, "New values are defined" ); @@ -206,7 +204,7 @@ QUnit.log(function( details ) { } var loc = details.module + ": " + details.name + ": ", output = "FAILED: " + loc + ( details.message ? details.message + ", " : "" ); - + if ( details.actual ) { output += "expected: " + details.expected + ", actual: " + details.actual; } @@ -226,20 +224,20 @@ QUnit.moduleStart(function( details ) { let Robot: any = () => {}; -QUnit.module( "robot", { +QUnit.module( "robot", { beforeEach: function() { this.robot = new Robot(); } }); - + QUnit.test( "say", function( assert ) { assert.ok( false, "I'm not quite ready yet" ); }); - + QUnit.test( "stomp", function( assert ) { assert.ok( false, "I'm not quite ready yet" ); }); - + // You're currently working on the laser feature, so we run only this test QUnit.only( "laser", function( assert ) { assert.ok( this.robot.laser() ); @@ -251,11 +249,11 @@ QUnit.module( "robot", { this.robot = new Robot(); } }); - + QUnit.test( "say", function( assert ) { assert.strictEqual( this.robot.say(), "Exterminate!" ); }); - + // Robot doesn't have a laser method, yet, skip this test // Will show up as skipped in the results QUnit.skip( "laser", function( assert ) { @@ -264,32 +262,32 @@ QUnit.skip( "laser", function( assert ) { QUnit.log( function( details ) { if ( details.result ) { - + // 5 is the line reference for the assertion method, not the following line. console.log( QUnit.stack( 5 ) ); } } ); - + QUnit.test( "foo", function( assert ) { - + // the log callback will report the position of the following line. assert.ok( true ); } ); QUnit.config.autostart = false; - + // require(["test/tests1.js", "test/tests2.js"], function() { (() => { QUnit.start(); })() // }); QUnit.test( "a test", function( assert ) { - + function square( x: number ) { return x * x; } - + var result = square( 2 ); - + assert.equal( result, 4, "square(2) equals 4" ); }); @@ -317,7 +315,7 @@ QUnit.test( "assert.async() test", function( assert ) { QUnit.test( "two async calls", function( assert ) { assert.expect( 2 ); - + var done1 = assert.async(); var done2 = assert.async(); setTimeout(function() { @@ -333,17 +331,17 @@ QUnit.test( "two async calls", function( assert ) { QUnit.test( "multiple call done()", function( assert ) { assert.expect( 3 ); var done = assert.async( 3 ); - + setTimeout(function() { assert.ok( true, "first call done." ); done(); }, 500 ); - + setTimeout(function() { assert.ok( true, "second call done." ); done(); }, 500 ); - + setTimeout(function() { assert.ok( true, "third call done." ); done(); @@ -353,14 +351,14 @@ QUnit.test( "multiple call done()", function( assert ) { QUnit.test( "deepEqual test", function( assert ) { var obj = { foo: "bar" }; - + assert.deepEqual( obj, { foo: "bar" }, "Two objects can be the same in value" ); }); QUnit.test( "ok test", function( assert ) { assert.ok( true, "true succeeds" ); assert.ok( "non-empty", "non-empty string succeeds" ); - + assert.ok( false, "false fails" ); assert.ok( 0, "0 fails" ); assert.ok( NaN, "NaN fails" ); @@ -378,30 +376,30 @@ QUnit.test( "equal test", function( assert ) { assert.equal( 0, 0, "Zero, Zero; equal succeeds" ); assert.equal( "", 0, "Empty, Zero; equal succeeds" ); assert.equal( "", "", "Empty, Empty; equal succeeds" ); - + assert.equal( "three", 3, "Three, 3; equal fails" ); assert.equal( null, false, "null, false; equal fails" ); }); QUnit.test( "a test", function( assert ) { assert.expect( 2 ); - + function calc( x: number, operation: (x:number)=> number ) { return operation( x ); } - + var result = calc( 2, function( x ) { assert.ok( true, "calc() calls operation function" ); return x * x; }); - + assert.equal( result, 4, "2 squared equals 4" ); }); QUnit.test( "notDeepEqual test", function( assert ) { var obj = { foo: "bar" }; - + assert.notDeepEqual( obj, { foo: "bla" }, "Different object, same key, different value, not equal" ); }); @@ -416,7 +414,7 @@ QUnit.test( "notOk test", function( assert ) { assert.notOk( NaN, "NaN succeeds" ); assert.notOk( null, "null succeeds" ); assert.notOk( undefined, "undefined succeeds" ); - + assert.notOk( true, "true fails" ); assert.notOk( 1, "1 fails" ); assert.notOk( "not-empty", "not-empty string fails" ); @@ -433,7 +431,7 @@ QUnit.test( "notPropEqual test", function( assert ) { this.y = y; this.z = z; } - + doA = function () {}; doB = function () {}; bar = 'prototype'; @@ -458,12 +456,12 @@ QUnit.test( "propEqual test", function( assert ) { this.y = y; this.z = z; } - + doA = function () {}; doB = function () {}; bar = 'prototype'; } - + var foo = new Foo( 1, "2", [] ); var bar: any = { x : 1, @@ -482,33 +480,33 @@ QUnit.test( "propEqual test", function( assert ) { // message: message // }); // }; - + // QUnit.test( "mod2", function( assert ) { // assert.expect( 2 ); - + // assert['mod2']( 2, 0, "2 % 2 == 0" ); // assert['mod2']( 3, 1, "3 % 2 == 1" ); // }); QUnit.test( "throws", function( assert ) { - + class CustomError { message: string; constructor(message: string) { - this.message = message; + this.message = message; } toString = function() { return this.message; } } - + assert.throws( function() { throw "error" }, "throws with just a message, not using the 'expected' argument" ); - + assert.throws( function() { throw new CustomError("some error description"); @@ -516,7 +514,7 @@ QUnit.test( "throws", function( assert ) { /description/, "raised error message contains 'description'" ); - + assert.throws( function() { throw new Error(); @@ -524,7 +522,7 @@ QUnit.test( "throws", function( assert ) { CustomError, "raised error is an instance of CustomError" ); - + assert.throws( function() { throw new CustomError("some error description"); @@ -532,7 +530,7 @@ QUnit.test( "throws", function( assert ) { new CustomError("some error description"), "raised error instance matches the CustomError instance" ); - + assert.throws( function() { throw new CustomError("some error description"); diff --git a/seamless-immutable/seamless-immutable.d.ts b/seamless-immutable/index.d.ts similarity index 97% rename from seamless-immutable/seamless-immutable.d.ts rename to seamless-immutable/index.d.ts index 44f049eb76..ceeccd7b3f 100644 --- a/seamless-immutable/seamless-immutable.d.ts +++ b/seamless-immutable/index.d.ts @@ -12,6 +12,8 @@ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +export = SeamlessImmutable; + declare namespace SeamlessImmutable { interface MergeConfig { deep?: boolean; @@ -58,8 +60,4 @@ declare namespace SeamlessImmutable { export function isImmutable(target: any): boolean; export function ImmutableError(message: string): Error; -} - -declare module "seamless-immutable" { - export = SeamlessImmutable; -} +} \ No newline at end of file diff --git a/seamless-immutable/seamless-immutable-tests.ts b/seamless-immutable/seamless-immutable-tests.ts index f250ea0a0c..745135b6a9 100644 --- a/seamless-immutable/seamless-immutable-tests.ts +++ b/seamless-immutable/seamless-immutable-tests.ts @@ -1,4 +1,3 @@ -/// import SI = require("seamless-immutable"); // Immutable instance method test diff --git a/seamless-immutable/tsconfig.json b/seamless-immutable/tsconfig.json new file mode 100644 index 0000000000..03b34432a7 --- /dev/null +++ b/seamless-immutable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "seamless-immutable-tests.ts" + ] +} \ No newline at end of file diff --git a/uritemplate/uritemplate.d.ts b/uritemplate/index.d.ts similarity index 100% rename from uritemplate/uritemplate.d.ts rename to uritemplate/index.d.ts diff --git a/uritemplate/tsconfig.json b/uritemplate/tsconfig.json new file mode 100644 index 0000000000..cfeb357411 --- /dev/null +++ b/uritemplate/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "uritemplate-tests.ts" + ] +} \ No newline at end of file diff --git a/uritemplate/uritemplate-tests.ts b/uritemplate/uritemplate-tests.ts index cd6e9737bd..07ce1dbcfb 100644 --- a/uritemplate/uritemplate-tests.ts +++ b/uritemplate/uritemplate-tests.ts @@ -1,4 +1,3 @@ -/// import { UriTemplate } from 'uritemplate'; @@ -14,7 +13,7 @@ function test_uritemplate() { pageNumber: 8 }); - // import module check + // import module check var expectedUrl = 'http://localhost/categories/shoes?sort=price&pageNumber=8'; if (expectedUrl != url) { throw `Expected ${expectedUrl}, got ${url}`; From 9742548d05dd7433ea6da088ac4120488e6092e9 Mon Sep 17 00:00:00 2001 From: Rufus Linke Date: Thu, 3 Nov 2016 08:59:06 +0100 Subject: [PATCH 051/131] add type definitions for angular-promise-tracker --- .../angular-promise-tracker-tests.ts | 22 ++++++++++++++++ .../angular-promise-tracker.d.ts | 26 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 angular-promise-tracker/angular-promise-tracker-tests.ts create mode 100644 angular-promise-tracker/angular-promise-tracker.d.ts diff --git a/angular-promise-tracker/angular-promise-tracker-tests.ts b/angular-promise-tracker/angular-promise-tracker-tests.ts new file mode 100644 index 0000000000..8c575567ff --- /dev/null +++ b/angular-promise-tracker/angular-promise-tracker-tests.ts @@ -0,0 +1,22 @@ +/// + +angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', + ($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { + const trackerWithoutOptions = promiseTracker(); + + const options = { + activationDelay: 10, + minDuration: 500 + } as angular.promisetracker.PromiseTrackerOptions; + const trackerWithOptions = promiseTracker(options); + + const isActive: boolean = trackerWithOptions.active(); + const tracking: boolean = trackerWithOptions.tracking(); + const trackingCount: number = trackerWithOptions.trackingCount(); + trackerWithOptions.cancel(); + + const createdPromise: angular.IDeferred = trackerWithOptions.createPromise(); + + const promiseToAdd = $q.defer().promise; + const addedPromise: angular.IDeferred = trackerWithOptions.addPromise(promiseToAdd); +}]); diff --git a/angular-promise-tracker/angular-promise-tracker.d.ts b/angular-promise-tracker/angular-promise-tracker.d.ts new file mode 100644 index 0000000000..28b6721fb7 --- /dev/null +++ b/angular-promise-tracker/angular-promise-tracker.d.ts @@ -0,0 +1,26 @@ +// Type definitions for angular-promise-tracker v2.2.2 +// Project: https://github.com/ajoslin/angular-promise-tracker +// Definitions by: Rufus Linke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.promisetracker { + interface PromiseTrackerOptions { + activationDelay: number; + minDuration: number; + } + + interface PromiseTracker { + active(): boolean; + tracking(): boolean; + trackingCount(): number; + addPromise(promise: angular.IPromise): angular.IDeferred; + createPromise(): angular.IDeferred; + cancel(): void; + } + + interface PromiseTrackerService { + (options?: PromiseTrackerOptions): PromiseTracker; + } +} From a2c847cc871734bf3f0c5a8695582c821c762efb Mon Sep 17 00:00:00 2001 From: Rufus Linke Date: Thu, 3 Nov 2016 11:06:48 +0100 Subject: [PATCH 052/131] adjust angular-promise-tracker typings to types-2.0 --- .../angular-promise-tracker-tests.ts | 4 +-- .../angular-promise-tracker.d.ts | 26 ---------------- angular-promise-tracker/index.d.ts | 30 +++++++++++++++++++ angular-promise-tracker/tsconfig.json | 19 ++++++++++++ 4 files changed, 50 insertions(+), 29 deletions(-) delete mode 100644 angular-promise-tracker/angular-promise-tracker.d.ts create mode 100644 angular-promise-tracker/index.d.ts create mode 100644 angular-promise-tracker/tsconfig.json diff --git a/angular-promise-tracker/angular-promise-tracker-tests.ts b/angular-promise-tracker/angular-promise-tracker-tests.ts index 8c575567ff..82f9e66c06 100644 --- a/angular-promise-tracker/angular-promise-tracker-tests.ts +++ b/angular-promise-tracker/angular-promise-tracker-tests.ts @@ -1,9 +1,7 @@ -/// - angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', ($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { const trackerWithoutOptions = promiseTracker(); - + const options = { activationDelay: 10, minDuration: 500 diff --git a/angular-promise-tracker/angular-promise-tracker.d.ts b/angular-promise-tracker/angular-promise-tracker.d.ts deleted file mode 100644 index 28b6721fb7..0000000000 --- a/angular-promise-tracker/angular-promise-tracker.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for angular-promise-tracker v2.2.2 -// Project: https://github.com/ajoslin/angular-promise-tracker -// Definitions by: Rufus Linke -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.promisetracker { - interface PromiseTrackerOptions { - activationDelay: number; - minDuration: number; - } - - interface PromiseTracker { - active(): boolean; - tracking(): boolean; - trackingCount(): number; - addPromise(promise: angular.IPromise): angular.IDeferred; - createPromise(): angular.IDeferred; - cancel(): void; - } - - interface PromiseTrackerService { - (options?: PromiseTrackerOptions): PromiseTracker; - } -} diff --git a/angular-promise-tracker/index.d.ts b/angular-promise-tracker/index.d.ts new file mode 100644 index 0000000000..91f7ad72e5 --- /dev/null +++ b/angular-promise-tracker/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for angular-promise-tracker 2.2.2 +// Project: https://github.com/ajoslin/angular-promise-tracker +// Definitions by: Rufus Linke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as angular from 'angular'; + +declare module 'angular' { + namespace promisetracker { + interface PromiseTrackerOptions { + activationDelay: number; + minDuration: number; + } + + interface PromiseTracker { + active(): boolean; + tracking(): boolean; + trackingCount(): number; + addPromise(promise: angular.IPromise): angular.IDeferred; + createPromise(): angular.IDeferred; + cancel(): void; + } + + interface PromiseTrackerService { + (options?: PromiseTrackerOptions): PromiseTracker; + } + } +} diff --git a/angular-promise-tracker/tsconfig.json b/angular-promise-tracker/tsconfig.json new file mode 100644 index 0000000000..266a8adf90 --- /dev/null +++ b/angular-promise-tracker/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-promise-tracker-tests.ts" + ] +} From 16b5c4a4fd4bcea7f83b32b760889558da240a60 Mon Sep 17 00:00:00 2001 From: Jesper Date: Thu, 3 Nov 2016 11:30:47 +0100 Subject: [PATCH 053/131] Solved export error in index.d.ts Please fill in this template. - [X] Prefer to make your PR against the `types-2.0` branch. - [X] The package does not provide its own types, and you can not add them. - [X] Test the change in your own code. - [X] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request). - [X] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes). If changing an existing definition: - [X] Provide a URL to documentation or source code which provides context for the suggested changes: There are no changes made to the API, only in how the module is exported. Thus no URL has been included as it's not relevant. - [X] Increase the version number in the header if appropriate. **Solution for error "error TS2694: Namespace 'angular' has no exported member 'gettext'.". Module "angular" is now imported. The "angular.gettext" namespace declaration has been changed to instead extend the angular module.** --- angular-gettext/index.d.ts | 112 +++++++++++++++++++------------------ 1 file changed, 59 insertions(+), 53 deletions(-) diff --git a/angular-gettext/index.d.ts b/angular-gettext/index.d.ts index 380ef1d8b7..224f5032e0 100644 --- a/angular-gettext/index.d.ts +++ b/angular-gettext/index.d.ts @@ -1,73 +1,79 @@ -// Type definitions for angular-gettext v2.1.0 +// Type definitions for angular-gettext v2.1.0 // Project: https://angular-gettext.rocketeer.be/ // Definitions by: Ákos Lukács // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare namespace angular.gettext { - interface gettextCatalog { - ////////////// - /// Fields /// - ////////////// - - /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ - debug: boolean; - /** (default: [MISSING]:): Custom prefix for untranslated strings. */ - debugPrefix: string; - /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ - showTranslatedMarkers: boolean; - /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ - translatedMarkerPrefix: string; - /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ - translatedMarkerSuffix: string; - /** An object of loaded translation strings.Shouldn't be used directly. */ - strings: {}; - /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated - * @deprecreated - */ - baseLanguage: string; +import * as angular from 'angular'; - /////////////// - /// Methods /// - /////////////// +declare module 'angular' { + export namespace gettext { + interface gettextCatalog { - /** Sets the current language and makes sure that all translations get updated correctly. */ - setCurrentLanguage(lang: string): void; + ////////////// + /// Fields /// + ////////////// - /** Returns the current language. */ - getCurrentLanguage(): string; + /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ + debug: boolean; + /** (default: [MISSING]:): Custom prefix for untranslated strings. */ + debugPrefix: string; + /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ + showTranslatedMarkers: boolean; + /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ + translatedMarkerPrefix: string; + /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ + translatedMarkerSuffix: string; + /** An object of loaded translation strings.Shouldn't be used directly. */ + strings: {}; + /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated + * @deprecreated + */ + baseLanguage: string; - /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ - * @param language A language code. - * @param strings A dictionary of strings. The format of this dictionary is: - * - Keys: Singular English strings (as defined in the source files) - * - Values: Either a single string for signular-only strings or an array of plural forms. - */ - setStrings(language: string, strings: { [key: string]: string|string[] }): void; - /** Get the correct pluralized (but untranslated) string for the value of n. */ - getStringForm(string: string, n: number): string; + /////////////// + /// Methods /// + /////////////// - /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: - * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); - * // var hello will be "Hallo Ruben!" in Dutch. - * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. - */ - getString(string: string, scope?: any, context?: string): string; + /** Sets the current language and makes sure that all translations get updated correctly. */ + setCurrentLanguage(lang: string): void; - /** Translate a plural string with the given context. */ - getPlural(n: number, string: string, stringPlural: string, context?: any): string; + /** Returns the current language. */ + getCurrentLanguage(): string; - /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ - loadRemote(url: string): ng.IHttpPromise; - } + /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ + * @param language A language code. + * @param strings A dictionary of strings. The format of this dictionary is: + * - Keys: Singular English strings (as defined in the source files) + * - Values: Either a single string for signular-only strings or an array of plural forms. + */ + setStrings(language: string, strings: { [key: string]: string|string[] }): void; - /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ - interface gettextFunction { - (dummyString: string): string; + /** Get the correct pluralized (but untranslated) string for the value of n. */ + getStringForm(string: string, n: number): string; + + /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: + * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); + * // var hello will be "Hallo Ruben!" in Dutch. + * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + */ + getString(string: string, scope?: any, context?: string): string; + + /** Translate a plural string with the given context. */ + getPlural(n: number, string: string, stringPlural: string, context?: any): string; + + /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ + loadRemote(url: string): ng.IHttpPromise; + } + + /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ + interface gettextFunction { + (dummyString: string): string; + } } } From 7e0ebfc5d209c654d86d30b6f54fae4a4ee498a8 Mon Sep 17 00:00:00 2001 From: Ray Solomon Date: Thu, 3 Nov 2016 19:59:30 -0700 Subject: [PATCH 054/131] Update bunyan LoggerOptions to accept stdSerializers --- bunyan/bunyan-tests.ts | 1 + bunyan/index.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bunyan/bunyan-tests.ts b/bunyan/bunyan-tests.ts index c609901b0a..06fce4b410 100644 --- a/bunyan/bunyan-tests.ts +++ b/bunyan/bunyan-tests.ts @@ -26,6 +26,7 @@ level = bunyan.resolveLevel(bunyan.FATAL); var options:bunyan.LoggerOptions = { name: 'test-logger', + serializers: bunyan.stdSerializers, streams: [{ type: 'stream', stream: process.stdout, diff --git a/bunyan/index.d.ts b/bunyan/index.d.ts index 79aa9e5f20..2983d8bb62 100644 --- a/bunyan/index.d.ts +++ b/bunyan/index.d.ts @@ -21,7 +21,7 @@ declare class Logger extends EventEmitter { levels(name: number | string, value: number | string): void; fields: any; - src:boolean; + src:boolean; trace(error: Error, format?: any, ...params: any[]): void; trace(buffer: Buffer, format?: any, ...params: any[]): void; @@ -54,7 +54,7 @@ interface LoggerOptions { streams?: Stream[]; level?: string | number; stream?: NodeJS.WritableStream; - serializers?: Serializers; + serializers?: Serializers | StdSerializers; src?: boolean; } From 093a21a7e5a7ab87057cf8b97a3385761223ec64 Mon Sep 17 00:00:00 2001 From: Bruce Lindsay Date: Fri, 4 Nov 2016 15:35:28 -0400 Subject: [PATCH 055/131] remove trailing whitespaces --- jquery/jquery-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 479081c477..3fe93e73a6 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -209,9 +209,9 @@ function test_ajax() { url: "test.js" }); jqXHR.abort('aborting because I can'); - + //Test the promise exposed by the jqXHR object - + // done method $.ajax({ url: "test.js" @@ -239,7 +239,7 @@ function test_ajax() { }).promise().always((jqXHR, textStatus, errorThrown) => { console.log(jqXHR, textStatus, errorThrown); }); - + // then method (as of 1.8) $.ajax({ url: "test.js" @@ -252,7 +252,7 @@ function test_ajax() { // generic then method var p: JQueryPromise = $.ajax({ url: "test.js" }).promise() .then(() => "Hello") - .then((x) => x.length); + .then((x) => x.length); } function test_ajaxComplete() { From a7baddf2ad0ab5b224d1d7c2800bcd966a4f0240 Mon Sep 17 00:00:00 2001 From: Bruce Lindsay Date: Fri, 4 Nov 2016 16:03:55 -0400 Subject: [PATCH 056/131] fix return type to include a chained promise --- jquery/index.d.ts | 2 +- jquery/jquery-tests.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/jquery/index.d.ts b/jquery/index.d.ts index f8af62caba..fa22a1599b 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -180,7 +180,7 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { /** * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R|JQueryPromise, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; /** * Property containing the parsed response if the response Content-Type is json */ diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 3fe93e73a6..c33967febd 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -169,6 +169,12 @@ function test_ajax() { console.log(data, textStatus, jqXHR); }); + // done method can change promise type through promise chaining + var chainedValuePromise : JQueryPromise; + chainedValuePromise = $.ajax({ + url: "test.js" + }).then(() => $.when(1)); + // fail method $.ajax({ url: "test.js" From c016b5b79fdc24e0db082ef50172746052703782 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 4 Nov 2016 13:42:08 -0700 Subject: [PATCH 057/131] Rename files --- bwip-js/{bwip-js.d.ts => index.d.ts} | 0 fossil-delta/{fossil-delta.d.ts => index.d.ts} | 0 gulp-cache/{gulp-cache.d.ts => index.d.ts} | 0 gulp-copy/{gulp-copy.d.ts => index.d.ts} | 0 koa-passport/{koa-passport.d.ts => index.d.ts} | 0 koa-session-minimal/{koa-session-minimal.d.ts => index.d.ts} | 0 .../{nodemailer-stub-transport.d.ts => index.d.ts} | 0 page-icon/{page-icon.d.ts => index.d.ts} | 0 react-side-effect/{react-side-effect.d.ts => index.d.ts} | 0 send/{send.d.ts => index.d.ts} | 0 sinon-mongoose/{sinon-mongoose.d.ts => index.d.ts} | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename bwip-js/{bwip-js.d.ts => index.d.ts} (100%) rename fossil-delta/{fossil-delta.d.ts => index.d.ts} (100%) rename gulp-cache/{gulp-cache.d.ts => index.d.ts} (100%) rename gulp-copy/{gulp-copy.d.ts => index.d.ts} (100%) rename koa-passport/{koa-passport.d.ts => index.d.ts} (100%) rename koa-session-minimal/{koa-session-minimal.d.ts => index.d.ts} (100%) rename nodemailer-stub-transport/{nodemailer-stub-transport.d.ts => index.d.ts} (100%) rename page-icon/{page-icon.d.ts => index.d.ts} (100%) rename react-side-effect/{react-side-effect.d.ts => index.d.ts} (100%) rename send/{send.d.ts => index.d.ts} (100%) rename sinon-mongoose/{sinon-mongoose.d.ts => index.d.ts} (100%) diff --git a/bwip-js/bwip-js.d.ts b/bwip-js/index.d.ts similarity index 100% rename from bwip-js/bwip-js.d.ts rename to bwip-js/index.d.ts diff --git a/fossil-delta/fossil-delta.d.ts b/fossil-delta/index.d.ts similarity index 100% rename from fossil-delta/fossil-delta.d.ts rename to fossil-delta/index.d.ts diff --git a/gulp-cache/gulp-cache.d.ts b/gulp-cache/index.d.ts similarity index 100% rename from gulp-cache/gulp-cache.d.ts rename to gulp-cache/index.d.ts diff --git a/gulp-copy/gulp-copy.d.ts b/gulp-copy/index.d.ts similarity index 100% rename from gulp-copy/gulp-copy.d.ts rename to gulp-copy/index.d.ts diff --git a/koa-passport/koa-passport.d.ts b/koa-passport/index.d.ts similarity index 100% rename from koa-passport/koa-passport.d.ts rename to koa-passport/index.d.ts diff --git a/koa-session-minimal/koa-session-minimal.d.ts b/koa-session-minimal/index.d.ts similarity index 100% rename from koa-session-minimal/koa-session-minimal.d.ts rename to koa-session-minimal/index.d.ts diff --git a/nodemailer-stub-transport/nodemailer-stub-transport.d.ts b/nodemailer-stub-transport/index.d.ts similarity index 100% rename from nodemailer-stub-transport/nodemailer-stub-transport.d.ts rename to nodemailer-stub-transport/index.d.ts diff --git a/page-icon/page-icon.d.ts b/page-icon/index.d.ts similarity index 100% rename from page-icon/page-icon.d.ts rename to page-icon/index.d.ts diff --git a/react-side-effect/react-side-effect.d.ts b/react-side-effect/index.d.ts similarity index 100% rename from react-side-effect/react-side-effect.d.ts rename to react-side-effect/index.d.ts diff --git a/send/send.d.ts b/send/index.d.ts similarity index 100% rename from send/send.d.ts rename to send/index.d.ts diff --git a/sinon-mongoose/sinon-mongoose.d.ts b/sinon-mongoose/index.d.ts similarity index 100% rename from sinon-mongoose/sinon-mongoose.d.ts rename to sinon-mongoose/index.d.ts From a1fbe3bc3f6d1256bd8635cc84c93cf8796c09ec Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 4 Nov 2016 13:23:57 -0700 Subject: [PATCH 058/131] Convert more packages to `types-2.0` style --- bootstrap-table/bootstrap-table-tests.ts | 1 + .../{bootstrap-table.d.ts => index.d.ts} | 2 +- bootstrap-table/tsconfig.json | 19 + bwip-js/bwip-js-tests.ts | 6 +- bwip-js/index.d.ts | 121 +++-- bwip-js/tsconfig.json | 19 + fossil-delta/fossil-delta-tests.ts | 1 - fossil-delta/index.d.ts | 13 +- fossil-delta/tsconfig.json | 19 + gulp-cache/gulp-cache-tests.ts | 5 +- gulp-cache/index.d.ts | 156 +++---- gulp-cache/tsconfig.json | 19 + gulp-copy/gulp-copy-tests.ts | 3 - gulp-copy/index.d.ts | 53 +-- gulp-copy/tsconfig.json | 19 + koa-passport/index.d.ts | 95 ++-- koa-passport/koa-passport-tests.ts | 3 - koa-passport/tsconfig.json | 19 + koa-session-minimal/index.d.ts | 58 ++- .../koa-session-minimal-tests.ts | 3 - koa-session-minimal/tsconfig.json | 19 + nodemailer-stub-transport/index.d.ts | 54 +-- .../nodemailer-stub-transport-tests.ts | 2 - nodemailer-stub-transport/tsconfig.json | 19 + page-icon/index.d.ts | 2 +- page-icon/page-icon-tests.ts | 2 - page-icon/tsconfig.json | 19 + passport-http/index.d.ts | 3 - react-side-effect/index.d.ts | 31 +- react-side-effect/react-side-effect-tests.ts | 2 - react-side-effect/tsconfig.json | 19 + send/index.d.ts | 439 +++++++++--------- send/send-tests.ts | 3 +- send/tsconfig.json | 19 + sinon-mongoose/index.d.ts | 7 +- sinon-mongoose/sinon-mongoose-tests.ts | 3 +- sinon-mongoose/tsconfig.json | 19 + 37 files changed, 730 insertions(+), 566 deletions(-) create mode 100644 bootstrap-table/bootstrap-table-tests.ts rename bootstrap-table/{bootstrap-table.d.ts => index.d.ts} (87%) create mode 100644 bootstrap-table/tsconfig.json create mode 100644 bwip-js/tsconfig.json create mode 100644 fossil-delta/tsconfig.json create mode 100644 gulp-cache/tsconfig.json create mode 100644 gulp-copy/tsconfig.json create mode 100644 koa-passport/tsconfig.json create mode 100644 koa-session-minimal/tsconfig.json create mode 100644 nodemailer-stub-transport/tsconfig.json create mode 100644 page-icon/tsconfig.json create mode 100644 react-side-effect/tsconfig.json create mode 100644 send/tsconfig.json create mode 100644 sinon-mongoose/tsconfig.json diff --git a/bootstrap-table/bootstrap-table-tests.ts b/bootstrap-table/bootstrap-table-tests.ts new file mode 100644 index 0000000000..6336ba4f8d --- /dev/null +++ b/bootstrap-table/bootstrap-table-tests.ts @@ -0,0 +1 @@ +$().bootstrapTable({}); diff --git a/bootstrap-table/bootstrap-table.d.ts b/bootstrap-table/index.d.ts similarity index 87% rename from bootstrap-table/bootstrap-table.d.ts rename to bootstrap-table/index.d.ts index d0356dff84..5ed1b5e529 100644 --- a/bootstrap-table/bootstrap-table.d.ts +++ b/bootstrap-table/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Talat Baig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface JQuery { bootstrapTable(options?: any): JQuery; diff --git a/bootstrap-table/tsconfig.json b/bootstrap-table/tsconfig.json new file mode 100644 index 0000000000..ad183f608a --- /dev/null +++ b/bootstrap-table/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-table-tests.ts" + ] +} \ No newline at end of file diff --git a/bwip-js/bwip-js-tests.ts b/bwip-js/bwip-js-tests.ts index 71601f111a..29cc419d2c 100644 --- a/bwip-js/bwip-js-tests.ts +++ b/bwip-js/bwip-js-tests.ts @@ -1,7 +1,3 @@ -/// -/// -'use strict'; - import * as bwipjs from 'bwip-js'; import * as http from 'http'; import * as fs from 'fs'; @@ -13,7 +9,7 @@ bwipjs.loadFont('Inconsolata', 108, http.createServer(function(req, res) { // If the url does not begin /?bcid= then 404. Otherwise, we end up // returning 400 on requests like favicon.ico. - if (req.url.indexOf('/?bcid=') != 0) { + if (req.url!.indexOf('/?bcid=') != 0) { res.writeHead(404, { 'Content-Type':'text/plain' }); res.end('BWIPJS: Unknown request format.', 'utf8'); } else { diff --git a/bwip-js/index.d.ts b/bwip-js/index.d.ts index 0f40b5771e..9c37fa6e44 100644 --- a/bwip-js/index.d.ts +++ b/bwip-js/index.d.ts @@ -3,84 +3,81 @@ // Definitions by: TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// -declare module 'bwip-js' { - import {IncomingMessage as Request, ServerResponse as Response} from 'http'; +import {IncomingMessage as Request, ServerResponse as Response} from 'http'; - module BwipJs { - export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void; - export function toBuffer(opts: ToBufferOptions, callback:(err: string|Error, png: Buffer) => void): void; - interface ToBufferOptions { - bcid: string; - text: string; +declare namespace BwipJs { + export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void; + export function toBuffer(opts: ToBufferOptions, callback:(err: string|Error, png: Buffer) => void): void; + interface ToBufferOptions { + bcid: string; + text: string; - parse?: boolean; - parsefunc?: boolean; + parse?: boolean; + parsefunc?: boolean; - height?: number; - width?: number; + height?: number; + width?: number; - scaleX?: number; - scaleY?: number; - scale?: number; + scaleX?: number; + scaleY?: number; + scale?: number; - rotate?: 'N'|'R'|'L'|'I'; + rotate?: 'N'|'R'|'L'|'I'; - paddingwidth?: number; - paddingheight?: number; + paddingwidth?: number; + paddingheight?: number; - monochrome?: boolean; - alttext?: boolean; + monochrome?: boolean; + alttext?: boolean; - includetext?: boolean; - textfont?: string; - textsize?: number; - textgaps?: number; + includetext?: boolean; + textfont?: string; + textsize?: number; + textgaps?: number; - textxalign?:'offleft'|'left'|'center'|'right'|'offright'|'justify'; - textyalign?:'below'|'center'|'above'; - textxoffset?: number; - textyoffset?: number; + textxalign?:'offleft'|'left'|'center'|'right'|'offright'|'justify'; + textyalign?:'below'|'center'|'above'; + textxoffset?: number; + textyoffset?: number; - showborder?: boolean; - borderwidth?: number; - borderleft?: number; - borderright?: number; - bordertop?: number; - boraderbottom?: number; + showborder?: boolean; + borderwidth?: number; + borderleft?: number; + borderright?: number; + bordertop?: number; + boraderbottom?: number; - barcolor?: string; - backgroundcolor?: string; - bordercolor?: string; - textcolor?: string; + barcolor?: string; + backgroundcolor?: string; + bordercolor?: string; + textcolor?: string; - addontextxoffset?: number; - addontextyoffset?: number; - addontextfont?: string; - addontextsize?: number; + addontextxoffset?: number; + addontextyoffset?: number; + addontextfont?: string; + addontextsize?: number; - guardwhitespace?: boolean; - guardwidth?: number; - guardheight?: number; - guardleftpos?: number; - guardrightpos?: number; - guardleftypos?: number; - guardrightypos?: number; + guardwhitespace?: boolean; + guardwidth?: number; + guardheight?: number; + guardleftpos?: number; + guardrightpos?: number; + guardleftypos?: number; + guardrightypos?: number; - sizelimit?: number; + sizelimit?: number; - includecheck?: boolean; - includecheckintext?: boolean; + includecheck?: boolean; + includecheckintext?: boolean; - inkspread?: number; - inkspreadh?: number; - inkspreadv?: number; - } + inkspread?: number; + inkspreadh?: number; + inkspreadv?: number; } - - - function BwipJs(req: Request, res: Response, opts?:BwipJs.ToBufferOptions): void; - - export = BwipJs; } + +declare function BwipJs(req: Request, res: Response, opts?:BwipJs.ToBufferOptions): void; + +export = BwipJs; diff --git a/bwip-js/tsconfig.json b/bwip-js/tsconfig.json new file mode 100644 index 0000000000..33e3e21f35 --- /dev/null +++ b/bwip-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bwip-js-tests.ts" + ] +} \ No newline at end of file diff --git a/fossil-delta/fossil-delta-tests.ts b/fossil-delta/fossil-delta-tests.ts index 113757c677..f3a7635a7c 100644 --- a/fossil-delta/fossil-delta-tests.ts +++ b/fossil-delta/fossil-delta-tests.ts @@ -1,4 +1,3 @@ -/// import * as fossilDelta from "fossil-delta"; var origin = new Array(1,2,3); diff --git a/fossil-delta/index.d.ts b/fossil-delta/index.d.ts index fddb8f50af..c72e914df6 100644 --- a/fossil-delta/index.d.ts +++ b/fossil-delta/index.d.ts @@ -3,11 +3,10 @@ // Definitions by: Endel Dreyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -declare module "fossil-delta" { - type ByteArray = Array | Uint8Array | Buffer; +/// - export function create(origin: ByteArray, target: ByteArray): Array; - export function apply(origin: ByteArray, delta: Array): Array; - export function outputSize(delta: Array): number; -} +type ByteArray = Array | Uint8Array | Buffer; + +export function create(origin: ByteArray, target: ByteArray): Array; +export function apply(origin: ByteArray, delta: Array): Array; +export function outputSize(delta: Array): number; diff --git a/fossil-delta/tsconfig.json b/fossil-delta/tsconfig.json new file mode 100644 index 0000000000..434d0761b7 --- /dev/null +++ b/fossil-delta/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fossil-delta-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-cache/gulp-cache-tests.ts b/gulp-cache/gulp-cache-tests.ts index 2efa3975fc..31df7b0259 100644 --- a/gulp-cache/gulp-cache-tests.ts +++ b/gulp-cache/gulp-cache-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as fs from "fs"; import * as gulp from "gulp"; import * as cache from "gulp-cache"; @@ -29,7 +26,7 @@ var jsHintVersion = '2.4.1', jshintOptions = fs.readFileSync('.jshintrc'); function makeHashKey(file: File) { - return [file.contents.toString('utf8'), jsHintVersion, jshintOptions].join(''); + return [(file.contents as Buffer).toString('utf8'), jsHintVersion, jshintOptions].join(''); } gulp.task('clear', function (done: any) { diff --git a/gulp-cache/index.d.ts b/gulp-cache/index.d.ts index cfb1cb2514..d576427f3d 100644 --- a/gulp-cache/index.d.ts +++ b/gulp-cache/index.d.ts @@ -3,92 +3,88 @@ // Definitions by: Arun Aravind // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// -declare module "gulp-cache" { - import File = require("vinyl"); - import { Transform } from "stream"; - import { PluginError } from "gulp-util"; +import File = require("vinyl"); +import { Transform } from "stream"; +import { PluginError } from "gulp-util"; - namespace gc { - type Predicate = (arg: T) => boolean; +declare namespace gc { + type Predicate = (arg: T) => boolean; - interface IGulpCacheOptions { - /** - * The cache instance to use for caching. - */ - fileCache?: IGulpCache; - - /** - * The name of the bucket which stores the cached objects. - * Default value = 'default' - */ - name?: string, - - /** - * The hash generator to use. - */ - key?: (file: File, callback?: (err: any, result: string) => void) => string | Promise; - - /** - * Value representing the success of a task. - */ - success?: boolean | Predicate; - - /** - * Content that is to be cached. - */ - value?: (result: any) => Object | Promise | string; - } - - interface ICacheOptions { - /** - * Specifies the name of the directory where the cache - * is to be stored. - */ - cacheDirName: string; - } - - interface IGulpCacheStatic { - /** - * Caches the result of a task. - * @param task The task whose result is to be cached. - */ - (task: NodeJS.ReadWriteStream): Transform; - - /** - * Caches the result of a task. - * @param task Task whose result is to be cached. - * @param options Override values for available settings. - */ - (task: NodeJS.ReadWriteStream, options: IGulpCacheOptions): Transform; - - clear(options: IGulpCacheOptions): Transform; - - /** - * Represents a cache store. - */ - Cache: IGulpCache; - - /** - * Purges the cache. - * @param err PluginError instance in case of a plugin error. - * If callback is not specified an exception of type - * 'PluginError' is thrown. - */ - clearAll(callback?: (err: PluginError) => void): void; - } + interface IGulpCacheOptions { + /** + * The cache instance to use for caching. + */ + fileCache?: IGulpCache; /** - * Represents a cach store. + * The name of the bucket which stores the cached objects. + * Default value = 'default' */ - interface IGulpCache { - new (options: ICacheOptions): any; - } + name?: string, + + /** + * The hash generator to use. + */ + key?: (file: File, callback?: (err: any, result: string) => void) => string | Promise; + + /** + * Value representing the success of a task. + */ + success?: boolean | Predicate; + + /** + * Content that is to be cached. + */ + value?: (result: any) => Object | Promise | string; } - const _: gc.IGulpCacheStatic; - export = _; + interface ICacheOptions { + /** + * Specifies the name of the directory where the cache + * is to be stored. + */ + cacheDirName: string; + } + + interface IGulpCacheStatic { + /** + * Caches the result of a task. + * @param task The task whose result is to be cached. + */ + (task: NodeJS.ReadWriteStream): Transform; + + /** + * Caches the result of a task. + * @param task Task whose result is to be cached. + * @param options Override values for available settings. + */ + (task: NodeJS.ReadWriteStream, options: IGulpCacheOptions): Transform; + + clear(options: IGulpCacheOptions): Transform; + + /** + * Represents a cache store. + */ + Cache: IGulpCache; + + /** + * Purges the cache. + * @param err PluginError instance in case of a plugin error. + * If callback is not specified an exception of type + * 'PluginError' is thrown. + */ + clearAll(callback?: (err: PluginError) => void): void; + } + + /** + * Represents a cach store. + */ + interface IGulpCache { + new (options: ICacheOptions): any; + } } + +declare const _: gc.IGulpCacheStatic; +export = _; diff --git a/gulp-cache/tsconfig.json b/gulp-cache/tsconfig.json new file mode 100644 index 0000000000..fb841a90ec --- /dev/null +++ b/gulp-cache/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-cache-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-copy/gulp-copy-tests.ts b/gulp-copy/gulp-copy-tests.ts index acb225bbe5..f4bc3ac023 100644 --- a/gulp-copy/gulp-copy-tests.ts +++ b/gulp-copy/gulp-copy-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as gulp from "gulp"; import * as gulpCopy from "gulp-copy"; diff --git a/gulp-copy/index.d.ts b/gulp-copy/index.d.ts index 68f652ed9a..18a85d1292 100644 --- a/gulp-copy/index.d.ts +++ b/gulp-copy/index.d.ts @@ -3,37 +3,32 @@ // Definitions by: Arun Aravind // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import through = require("through"); -declare module "gulp-copy" { - import through = require("through"); +/** + * Copy files to destination and expose those files as source streams for the gulp pipeline. + * + * @param outDirectory The name of the destination directory. If this directory + * does not exist, it will be created atomatically. + */ +declare function gulpCopy(outDirectory: string): through.ThroughStream; - /** - * Copy files to destination and expose those files as source streams for the gulp pipeline. - * - * @param outDirectory The name of the destination directory. If this directory - * does not exist, it will be created atomatically. - */ - function gulpCopy(outDirectory: string): through.ThroughStream; +/** + * Copy files to destination and expose those files as source streams for the gulp pipeline. + * + * @param outDirectory The name of the destination directory. If this directory + * does not exist, it will be created atomatically. + * @param options Override values for available settings. + */ +declare function gulpCopy(outDirectory: string, options: gulpCopy.GulpCopyOptions): through.ThroughStream; - /** - * Copy files to destination and expose those files as source streams for the gulp pipeline. - * - * @param outDirectory The name of the destination directory. If this directory - * does not exist, it will be created atomatically. - * @param options Override values for available settings. - */ - function gulpCopy(outDirectory: string, options: gulpCopy.GulpCopyOptions): through.ThroughStream; - - namespace gulpCopy { - - export interface GulpCopyOptions { - /** - * Specifies the number of parts of the path to be ignored as path prefixes. - */ - prefix: number; - } +declare namespace gulpCopy { + export interface GulpCopyOptions { + /** + * Specifies the number of parts of the path to be ignored as path prefixes. + */ + prefix: number; } - - export = gulpCopy; } + +export = gulpCopy; diff --git a/gulp-copy/tsconfig.json b/gulp-copy/tsconfig.json new file mode 100644 index 0000000000..052c9b42f7 --- /dev/null +++ b/gulp-copy/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-copy-tests.ts" + ] +} \ No newline at end of file diff --git a/koa-passport/index.d.ts b/koa-passport/index.d.ts index f89d534ee2..f17bf87f39 100644 --- a/koa-passport/index.d.ts +++ b/koa-passport/index.d.ts @@ -10,59 +10,54 @@ app.use(passport.session()); =============================================== */ -/// -/// -declare module "koa-passport" { +import * as Koa from "koa"; +declare module "koa" { + interface Request { + authInfo?: any; + user?: any; - import * as Koa from "koa"; - module "koa" { - interface Request { - authInfo?: any; - user?: any; + login(user: any): Promise; + login(user: any, options: Object): Promise; + logIn(user: any): Promise; + logIn(user: any, options: Object): Promise; - login(user: any): Promise; - login(user: any, options: Object): Promise; - logIn(user: any): Promise; - logIn(user: any, options: Object): Promise; + logout(): void; + logOut(): void; - logout(): void; - logOut(): void; - - isAuthenticated(): boolean; - isUnauthenticated(): boolean; - } + isAuthenticated(): boolean; + isUnauthenticated(): boolean; } - - import * as passport from "passport"; - - interface Middleware { (ctx: Koa.Context, next: () => Promise): any; } - interface KoaPassport { - use(strategy: passport.Strategy): this; - use(name: string, strategy: passport.Strategy): this; - unuse(name: string): this; - framework(fw: passport.Framework): this; - initialize(options?: { userProperty: string; }): Middleware; - session(options?: { pauseStream: boolean; }): Middleware; - - authenticate(strategy: string, callback?: Function): Middleware; - authenticate(strategy: string, options: Object, callback?: Function): Middleware; - authenticate(strategies: string[], callback?: Function): Middleware; - authenticate(strategies: string[], options: Object, callback?: Function): Middleware; - authorize(strategy: string, callback?: Function): Middleware; - authorize(strategy: string, options: Object, callback?: Function): Middleware; - authorize(strategies: string[], callback?: Function): Middleware; - authorize(strategies: string[], options: Object, callback?: Function): Middleware; - serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; - deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; - transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; - } - const koaPassport: KoaPassport; - - namespace KoaPassport { - interface Profile extends passport.Profile { } - interface Framework extends passport.Framework { } - } - - export = koaPassport; } + +import * as passport from "passport"; + +interface Middleware { (ctx: Koa.Context, next: () => Promise): any; } +interface KoaPassport { + use(strategy: passport.Strategy): this; + use(name: string, strategy: passport.Strategy): this; + unuse(name: string): this; + framework(fw: passport.Framework): this; + initialize(options?: { userProperty: string; }): Middleware; + session(options?: { pauseStream: boolean; }): Middleware; + + authenticate(strategy: string, callback?: Function): Middleware; + authenticate(strategy: string, options: Object, callback?: Function): Middleware; + authenticate(strategies: string[], callback?: Function): Middleware; + authenticate(strategies: string[], options: Object, callback?: Function): Middleware; + authorize(strategy: string, callback?: Function): Middleware; + authorize(strategy: string, options: Object, callback?: Function): Middleware; + authorize(strategies: string[], callback?: Function): Middleware; + authorize(strategies: string[], options: Object, callback?: Function): Middleware; + serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; + deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; + transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; +} +declare const koaPassport: KoaPassport; + +declare namespace KoaPassport { + interface Profile extends passport.Profile { } + interface Framework extends passport.Framework { } +} + +export = koaPassport; diff --git a/koa-passport/koa-passport-tests.ts b/koa-passport/koa-passport-tests.ts index cdfe4938f4..eebb67a3b1 100644 --- a/koa-passport/koa-passport-tests.ts +++ b/koa-passport/koa-passport-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as Koa from 'koa'; import * as passport from 'koa-passport'; diff --git a/koa-passport/tsconfig.json b/koa-passport/tsconfig.json new file mode 100644 index 0000000000..8e0b10ae18 --- /dev/null +++ b/koa-passport/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-passport-tests.ts" + ] +} \ No newline at end of file diff --git a/koa-session-minimal/index.d.ts b/koa-session-minimal/index.d.ts index e0369fcc1b..1c55660dc9 100644 --- a/koa-session-minimal/index.d.ts +++ b/koa-session-minimal/index.d.ts @@ -13,38 +13,32 @@ =============================================== */ -/// -/// +import * as Koa from "koa"; +import * as cookies from "cookies"; -declare module "koa-session-minimal" { - - import * as Koa from "koa"; - import * as cookies from "cookies"; - - module "koa" { - interface Request { - session: any; - sessionHandler: { regenerateId: () => void }; - } +declare module "koa" { + interface Request { + session: any; + sessionHandler: { regenerateId: () => void }; } - - function session(opts?: { - /** - * session cookie name and store key prefix. Default is 'koa:sess' - */ - key?: string; - - /** - * cookie options - */ - cookie?: cookies.IOptions | { (ctx?: Koa.Context): cookies.IOptions }; - - /** - * session store - */ - store?: any; - }): { (ctx: Koa.Context, next?: () => any): any }; - - namespace session {} - export = session; } + +declare function session(opts?: { + /** + * session cookie name and store key prefix. Default is 'koa:sess' + */ + key?: string; + + /** + * cookie options + */ + cookie?: cookies.IOptions | { (ctx?: Koa.Context): cookies.IOptions }; + + /** + * session store + */ + store?: any; +}): { (ctx: Koa.Context, next?: () => any): any }; + +declare namespace session {} +export = session; diff --git a/koa-session-minimal/koa-session-minimal-tests.ts b/koa-session-minimal/koa-session-minimal-tests.ts index 7ee723d3aa..b58f441d8e 100644 --- a/koa-session-minimal/koa-session-minimal-tests.ts +++ b/koa-session-minimal/koa-session-minimal-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as Koa from "koa"; import * as session from "koa-session-minimal"; diff --git a/koa-session-minimal/tsconfig.json b/koa-session-minimal/tsconfig.json new file mode 100644 index 0000000000..d269751272 --- /dev/null +++ b/koa-session-minimal/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-session-minimal-tests.ts" + ] +} \ No newline at end of file diff --git a/nodemailer-stub-transport/index.d.ts b/nodemailer-stub-transport/index.d.ts index 36eca75240..5bae849df7 100644 --- a/nodemailer-stub-transport/index.d.ts +++ b/nodemailer-stub-transport/index.d.ts @@ -3,36 +3,32 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare module "nodemailer-stub-transport" { - import * as nodemailer from "nodemailer"; - - namespace StubTransportStatic { - /** - * Options. - * @interface - */ - export interface Options { - /** - * Specifies a custom error. - * @type {any} - */ - error?: any; - - /** - * Value that indicates if the BCC addresses must be included in generated message. - * @type {boolean} - */ - keepBcc?: boolean; - } - } +import * as nodemailer from "nodemailer"; +declare namespace StubTransportStatic { /** - * Creates a stub transport. - * @param {Options} [options] Options. - * @return {Transport} The stub transport. + * Options. + * @interface */ - function stubTransport(options?: StubTransportStatic.Options): nodemailer.Transport; - export = stubTransport; + export interface Options { + /** + * Specifies a custom error. + * @type {any} + */ + error?: any; + + /** + * Value that indicates if the BCC addresses must be included in generated message. + * @type {boolean} + */ + keepBcc?: boolean; + } } + +/** + * Creates a stub transport. + * @param {Options} [options] Options. + * @return {Transport} The stub transport. + */ +declare function stubTransport(options?: StubTransportStatic.Options): nodemailer.Transport; +export = stubTransport; diff --git a/nodemailer-stub-transport/nodemailer-stub-transport-tests.ts b/nodemailer-stub-transport/nodemailer-stub-transport-tests.ts index e77bf89b41..b232717739 100644 --- a/nodemailer-stub-transport/nodemailer-stub-transport-tests.ts +++ b/nodemailer-stub-transport/nodemailer-stub-transport-tests.ts @@ -1,5 +1,3 @@ -/// - import nodemailer = require("nodemailer"); import stubTransport = require("nodemailer-stub-transport"); diff --git a/nodemailer-stub-transport/tsconfig.json b/nodemailer-stub-transport/tsconfig.json new file mode 100644 index 0000000000..655c43e6de --- /dev/null +++ b/nodemailer-stub-transport/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "nodemailer-stub-transport-tests.ts" + ] +} \ No newline at end of file diff --git a/page-icon/index.d.ts b/page-icon/index.d.ts index 1e183ea289..60db62caa9 100644 --- a/page-icon/index.d.ts +++ b/page-icon/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PageIcon { interface Icon { diff --git a/page-icon/page-icon-tests.ts b/page-icon/page-icon-tests.ts index 88dac1b6aa..4a6bc8c2b6 100644 --- a/page-icon/page-icon-tests.ts +++ b/page-icon/page-icon-tests.ts @@ -1,5 +1,3 @@ -/// - import * as pageIcon from "page-icon"; const siteUrl = "https://www.facebook.com/"; diff --git a/page-icon/tsconfig.json b/page-icon/tsconfig.json new file mode 100644 index 0000000000..1af988fca2 --- /dev/null +++ b/page-icon/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "page-icon-tests.ts" + ] +} \ No newline at end of file diff --git a/passport-http/index.d.ts b/passport-http/index.d.ts index 8efefc0c95..efd474404d 100644 --- a/passport-http/index.d.ts +++ b/passport-http/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Christophe Vidal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - import passport = require("passport"); import express = require("express"); diff --git a/react-side-effect/index.d.ts b/react-side-effect/index.d.ts index edca0f08e8..ed76d56af4 100644 --- a/react-side-effect/index.d.ts +++ b/react-side-effect/index.d.ts @@ -3,25 +3,20 @@ // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import React = require("react"); -declare module "react-side-effect" { +declare function withSideEffect( + reducePropsToState: (propsList: any[]) => any, + handleStateChangeOnClient: (state: any) => any, + mapStateOnServer?: (state: any) => any +): ClassDecorator; - import React = __React; +declare class ElementClass extends React.Component {} - function withSideEffect( - reducePropsToState: (propsList: any[]) => any, - handleStateChangeOnClient: (state: any) => any, - mapStateOnServer?: (state: any) => any - ): ClassDecorator; - - class ElementClass extends React.Component {} - - interface ClassDecorator { - (component:T): T; - } - - namespace withSideEffect {} // https://github.com/Microsoft/TypeScript/issues/5073 - - export = withSideEffect; +interface ClassDecorator { + (component:T): T; } + +declare namespace withSideEffect {} // https://github.com/Microsoft/TypeScript/issues/5073 + +export = withSideEffect; diff --git a/react-side-effect/react-side-effect-tests.ts b/react-side-effect/react-side-effect-tests.ts index 8dab67d235..353b0754f5 100644 --- a/react-side-effect/react-side-effect-tests.ts +++ b/react-side-effect/react-side-effect-tests.ts @@ -1,5 +1,3 @@ -/// - import * as React from "react"; import * as withSideEffect from "react-side-effect"; diff --git a/react-side-effect/tsconfig.json b/react-side-effect/tsconfig.json new file mode 100644 index 0000000000..47bcf759b7 --- /dev/null +++ b/react-side-effect/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-side-effect-tests.ts" + ] +} \ No newline at end of file diff --git a/send/index.d.ts b/send/index.d.ts index d48a66cc23..4b738fa011 100644 --- a/send/index.d.ts +++ b/send/index.d.ts @@ -3,240 +3,237 @@ // Definitions by: Mike Jerred // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// -declare module "send" { - import * as stream from "stream"; - import * as fs from "fs"; +import * as stream from "stream"; +import * as fs from "fs"; - /** - * Create a new SendStream for the given path to send to a res. - * The req is the Node.js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path). - */ - function send(req: stream.Readable, path: string, options?: send.SendOptions): send.SendStream; +/** + * Create a new SendStream for the given path to send to a res. + * The req is the Node.js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path). + */ +declare function send(req: stream.Readable, path: string, options?: send.SendOptions): send.SendStream; - import * as m from "mime"; +import * as m from "mime"; - namespace send { - var mime: typeof m; - interface SendOptions { - /** - * Enable or disable accepting ranged requests, defaults to true. - * Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. - */ - acceptRanges?: boolean; +declare namespace send { + var mime: typeof m; + interface SendOptions { + /** + * Enable or disable accepting ranged requests, defaults to true. + * Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. + */ + acceptRanges?: boolean; - /** - * Enable or disable setting Cache-Control response header, defaults to true. - * Disabling this will ignore the maxAge option. - */ - cacheControl?: boolean; + /** + * Enable or disable setting Cache-Control response header, defaults to true. + * Disabling this will ignore the maxAge option. + */ + cacheControl?: boolean; - /** - * Set how "dotfiles" are treated when encountered. - * A dotfile is a file or directory that begins with a dot ("."). - * Note this check is done on the path itself without checking if the path actually exists on the disk. - * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). - * 'allow' No special treatment for dotfiles. - * 'deny' Send a 403 for any request for a dotfile. - * 'ignore' Pretend like the dotfile does not exist and 404. - * The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility. - */ - dotfiles?: "allow" | "deny" | "ignore"; + /** + * Set how "dotfiles" are treated when encountered. + * A dotfile is a file or directory that begins with a dot ("."). + * Note this check is done on the path itself without checking if the path actually exists on the disk. + * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). + * 'allow' No special treatment for dotfiles. + * 'deny' Send a 403 for any request for a dotfile. + * 'ignore' Pretend like the dotfile does not exist and 404. + * The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility. + */ + dotfiles?: "allow" | "deny" | "ignore"; - /** - * Byte offset at which the stream ends, defaults to the length of the file minus 1. - * The end is inclusive in the stream, meaning end: 3 will include the 4th byte in the stream. - */ - end?: number; + /** + * Byte offset at which the stream ends, defaults to the length of the file minus 1. + * The end is inclusive in the stream, meaning end: 3 will include the 4th byte in the stream. + */ + end?: number; - /** - * Enable or disable etag generation, defaults to true. - */ - etag?: boolean; + /** + * Enable or disable etag generation, defaults to true. + */ + etag?: boolean; - /** - * If a given file doesn't exist, try appending one of the given extensions, in the given order. - * By default, this is disabled (set to false). - * An example value that will serve extension-less HTML files: ['html', 'htm']. - * This is skipped if the requested file already has an extension. - */ - extensions?: string[] | string | boolean; + /** + * If a given file doesn't exist, try appending one of the given extensions, in the given order. + * By default, this is disabled (set to false). + * An example value that will serve extension-less HTML files: ['html', 'htm']. + * This is skipped if the requested file already has an extension. + */ + extensions?: string[] | string | boolean; - /** - * By default send supports "index.html" files, to disable this set false or to supply a new index pass a string or an array in preferred order. - */ - index?: string[] | string | boolean; + /** + * By default send supports "index.html" files, to disable this set false or to supply a new index pass a string or an array in preferred order. + */ + index?: string[] | string | boolean; - /** - * Enable or disable Last-Modified header, defaults to true. - * Uses the file system's last modified value. - */ - lastModified?: boolean; + /** + * Enable or disable Last-Modified header, defaults to true. + * Uses the file system's last modified value. + */ + lastModified?: boolean; - /** - * Provide a max-age in milliseconds for http caching, defaults to 0. - * This can also be a string accepted by the ms module. - */ - maxAge?: string | number; + /** + * Provide a max-age in milliseconds for http caching, defaults to 0. + * This can also be a string accepted by the ms module. + */ + maxAge?: string | number; - /** - * Serve files relative to path. - */ - root?: string; + /** + * Serve files relative to path. + */ + root?: string; - /** - * Byte offset at which the stream starts, defaults to 0. - * The start is inclusive, meaning start: 2 will include the 3rd byte in the stream. - */ - start?: number; - } - - interface SendStream extends stream.Stream { - /** - * @deprecated pass etag as option - * Enable or disable etag generation. - */ - etag(val: boolean): SendStream; - - /** - * @deprecated use dotfiles option - * Enable or disable "hidden" (dot) files. - */ - hidden(val: boolean): SendStream; - - /** - * @deprecated pass index as option - * Set index `paths`, set to a falsy value to disable index support. - */ - index(paths: string[] | string): SendStream; - - /** - * @deprecated pass root as option - * Set root `path`. - */ - root(paths: string): SendStream; - - /** - * @deprecated pass root as option - * Set root `path`. - */ - from(paths: string): SendStream; - - /** - * @deprecated pass maxAge as option - * Set max-age to `maxAge`. - */ - maxage(maxAge: string | number): SendStream; - - /** - * Emit error with `status`. - * @private - */ - error(status: number, error?: Error): void; - - /** - * Check if the pathname ends with "/". - * @private - */ - hasTrailingSlash(): boolean; - - /** - * Check if this is a conditional GET request. - * @private - */ - isConditionalGET(): boolean; - - /** - * Strip content-* header fields. - * @private - */ - removeContentHeaderFields(): void; - - /** - * Respond with 304 not modified. - * @private - */ - notModified(): void; - - /** - * Raise error that headers already sent. - * @private - */ - headersAlreadySent(): void; - - /** - * Check if the request is cacheable, aka responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). - * @private - */ - isCachable(): boolean; - - /** - * Handle stat() error. - * @private - */ - onStatError(error: Error): void; - - /** - * Check if the cache is fresh. - * @private - */ - isFresh(): boolean; - - /** - * Check if the range is fresh. - * @private - */ - isRangeFresh(): boolean; - - /** - * Redirect to path. - * @private - */ - redirect(path: string): void; - - /** - * Pipe to `res`. - */ - pipe(res: stream.Writable): stream.Writable; - - /** - * Transfer `path`. - */ - send(path: string, stat?: fs.Stats): void; - - /** - * Transfer file for `path`. - * @private - */ - sendFile(path: string): void; - - /** - * Transfer index for `path`. - * @private - */ - sendIndex(path: string): void; - - /** - * Transfer index for `path`. - * @private - */ - stream(path: string, options?: {}): void; - - /** - * Set content-type based on `path` if it hasn't been explicitly set. - * @private - */ - type(path: string): void; - - /** - * Set response header fields, most fields may be pre-defined. - * @private - */ - setHeader(path: string, stat: fs.Stats): void; - } + /** + * Byte offset at which the stream starts, defaults to 0. + * The start is inclusive, meaning start: 2 will include the 3rd byte in the stream. + */ + start?: number; } - export = send; -} \ No newline at end of file + interface SendStream extends stream.Stream { + /** + * @deprecated pass etag as option + * Enable or disable etag generation. + */ + etag(val: boolean): SendStream; + + /** + * @deprecated use dotfiles option + * Enable or disable "hidden" (dot) files. + */ + hidden(val: boolean): SendStream; + + /** + * @deprecated pass index as option + * Set index `paths`, set to a falsy value to disable index support. + */ + index(paths: string[] | string): SendStream; + + /** + * @deprecated pass root as option + * Set root `path`. + */ + root(paths: string): SendStream; + + /** + * @deprecated pass root as option + * Set root `path`. + */ + from(paths: string): SendStream; + + /** + * @deprecated pass maxAge as option + * Set max-age to `maxAge`. + */ + maxage(maxAge: string | number): SendStream; + + /** + * Emit error with `status`. + * @private + */ + error(status: number, error?: Error): void; + + /** + * Check if the pathname ends with "/". + * @private + */ + hasTrailingSlash(): boolean; + + /** + * Check if this is a conditional GET request. + * @private + */ + isConditionalGET(): boolean; + + /** + * Strip content-* header fields. + * @private + */ + removeContentHeaderFields(): void; + + /** + * Respond with 304 not modified. + * @private + */ + notModified(): void; + + /** + * Raise error that headers already sent. + * @private + */ + headersAlreadySent(): void; + + /** + * Check if the request is cacheable, aka responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * @private + */ + isCachable(): boolean; + + /** + * Handle stat() error. + * @private + */ + onStatError(error: Error): void; + + /** + * Check if the cache is fresh. + * @private + */ + isFresh(): boolean; + + /** + * Check if the range is fresh. + * @private + */ + isRangeFresh(): boolean; + + /** + * Redirect to path. + * @private + */ + redirect(path: string): void; + + /** + * Pipe to `res`. + */ + pipe(res: stream.Writable): stream.Writable; + + /** + * Transfer `path`. + */ + send(path: string, stat?: fs.Stats): void; + + /** + * Transfer file for `path`. + * @private + */ + sendFile(path: string): void; + + /** + * Transfer index for `path`. + * @private + */ + sendIndex(path: string): void; + + /** + * Transfer index for `path`. + * @private + */ + stream(path: string, options?: {}): void; + + /** + * Set content-type based on `path` if it hasn't been explicitly set. + * @private + */ + type(path: string): void; + + /** + * Set response header fields, most fields may be pre-defined. + * @private + */ + setHeader(path: string, stat: fs.Stats): void; + } +} + +export = send; diff --git a/send/send-tests.ts b/send/send-tests.ts index 25a3e457ee..22e3e171f2 100644 --- a/send/send-tests.ts +++ b/send/send-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// import * as express from 'express'; import * as send from 'send'; diff --git a/send/tsconfig.json b/send/tsconfig.json new file mode 100644 index 0000000000..3d9a6c0bd6 --- /dev/null +++ b/send/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "send-tests.ts" + ] +} \ No newline at end of file diff --git a/sinon-mongoose/index.d.ts b/sinon-mongoose/index.d.ts index 13e8a3f3a6..f2d15651e8 100644 --- a/sinon-mongoose/index.d.ts +++ b/sinon-mongoose/index.d.ts @@ -3,16 +3,13 @@ // Definitions by: stevehipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare namespace Sinon { +import * as s from "sinon"; +declare module "sinon" { export interface SinonStub { - /** * When called, the stub will create a new stub to represent a mongoose chained function. */ chain(name: string): SinonStub } - } diff --git a/sinon-mongoose/sinon-mongoose-tests.ts b/sinon-mongoose/sinon-mongoose-tests.ts index 1d32e25776..b16ed166eb 100644 --- a/sinon-mongoose/sinon-mongoose-tests.ts +++ b/sinon-mongoose/sinon-mongoose-tests.ts @@ -1,4 +1,5 @@ -/// +import * as sinon from "sinon"; + function testChain() { sinon.stub().chain('exec'); } diff --git a/sinon-mongoose/tsconfig.json b/sinon-mongoose/tsconfig.json new file mode 100644 index 0000000000..e7413b6c50 --- /dev/null +++ b/sinon-mongoose/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sinon-mongoose-tests.ts" + ] +} \ No newline at end of file From 57556c944d19fe551bd2f796d841ea09ea280971 Mon Sep 17 00:00:00 2001 From: bruce-lindsay Date: Fri, 4 Nov 2016 17:24:36 -0400 Subject: [PATCH 059/131] Update jquery-tests.ts fixed comment --- jquery/jquery-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index c33967febd..b64fdc43cf 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -169,7 +169,7 @@ function test_ajax() { console.log(data, textStatus, jqXHR); }); - // done method can change promise type through promise chaining + // then method can change promise type through promise chaining var chainedValuePromise : JQueryPromise; chainedValuePromise = $.ajax({ url: "test.js" From 0c861b0b4ceae3e1a15f57ad1da9735a7006196c Mon Sep 17 00:00:00 2001 From: Philipp A Date: Sat, 5 Nov 2016 20:36:47 +0100 Subject: [PATCH 060/131] Added event-to-promise definition (#12502) --- event-to-promise/event-to-promise-tests.ts | 21 ++++++++++ event-to-promise/index.d.ts | 45 ++++++++++++++++++++++ event-to-promise/tsconfig.json | 19 +++++++++ 3 files changed, 85 insertions(+) create mode 100644 event-to-promise/event-to-promise-tests.ts create mode 100644 event-to-promise/index.d.ts create mode 100644 event-to-promise/tsconfig.json diff --git a/event-to-promise/event-to-promise-tests.ts b/event-to-promise/event-to-promise-tests.ts new file mode 100644 index 0000000000..2b99ddc62f --- /dev/null +++ b/event-to-promise/event-to-promise-tests.ts @@ -0,0 +1,21 @@ +import { EventEmitter } from 'events' + +import * as eventToPromise from 'event-to-promise' + + +{ + const ee = new EventEmitter() + const ep = eventToPromise(ee, 'custom') + + ep.then(console.log) + ee.emit('custom') +} + + +{ + const et = new EventTarget() + const tp = eventToPromise.multi(et, ['custom']) + + tp.then(console.log) + et.dispatchEvent(new Event('custom')) +} diff --git a/event-to-promise/index.d.ts b/event-to-promise/index.d.ts new file mode 100644 index 0000000000..aa491f0b0e --- /dev/null +++ b/event-to-promise/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for event-to-promise v0.7.0 +// Project: https://github.com/JsCommunity/event-to-promise +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events' + +type EventSource = EventEmitter | EventTarget + +interface EventToPromiseOptions { + /** If true, all parameters of the emitted events are put in an array which is used to resolve/reject the promise. (default: `false`) */ + array?: boolean, + /** The name of the event which rejects the promise. (default: `'error'`) */ + error?: string, + /** Whether the error event should be ignored and not reject the promise. (default: `false`) */ + ignoreErrors?: boolean, +} + +/** + * Wait for one event. The first parameter of the emitted event is used to resolve/reject the promise. + * + * @param emitter The event emitter you want to watch an event on. + * @param event The name of the event you want to watch. + * @param options An `Object` controlling advanced options. + * @return The returned promise has a `cancel()` method which can be used to remove the event listeners. Note that the promise will never settled if canceled. + */ +declare function eventToPromise(emitter: EventSource, event: string, options?: EventToPromiseOptions): Promise; + +declare namespace eventToPromise { + /** + * Wait for one of multiple events. The array of all the parameters of the emitted event is used to resolve/reject the promise. + * + * The array also has an event property indicating which event has been emitted. + * + * @param emitter The event emitter you want to watch an event on. + * @param successEvents The names of the events which resolve the promise. + * @param errorEvents The names of the events which reject the promise. (default: `['error']`) + * @return The returned promise has a `cancel()` method which can be used to remove the event listeners. Note that the promise will never settled if canceled. + */ + export function multi(emitter: EventSource, successEvents: string[], errorEvents?: string[]): Promise; +} + +export = eventToPromise diff --git a/event-to-promise/tsconfig.json b/event-to-promise/tsconfig.json new file mode 100644 index 0000000000..d5fd4f1e8e --- /dev/null +++ b/event-to-promise/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "event-to-promise-tests.ts" + ] +} From d2150a603fd8a2a03672eb8707834ffde2aed278 Mon Sep 17 00:00:00 2001 From: Andy Date: Sat, 5 Nov 2016 13:34:11 -0700 Subject: [PATCH 061/131] Even more 2.0 (#12503) * Always use forceConsistentCasingInFileNames * Rename files * Convert more packages to `types-2.0` style --- angular-animate/tsconfig.json | 2 +- angular-cookies/tsconfig.json | 2 +- angular-deferred-bootstrap/tsconfig.json | 2 +- angular-mocks/tsconfig.json | 2 +- angular-q-spread/tsconfig.json | 2 +- angular-resource/tsconfig.json | 2 +- angular-route/tsconfig.json | 2 +- angular-sanitize/tsconfig.json | 2 +- angular-websocket/tsconfig.json | 2 +- angular-xeditable/tsconfig.json | 2 +- angular/tsconfig.json | 2 +- async-polling/async-polling-tests.ts | 4 +- async-polling/async-polling.d.ts | 18 ----- async-polling/index.d.ts | 16 +++++ async-polling/tsconfig.json | 19 +++++ awesomplete/awesomplete-tests.ts | 2 - awesomplete/{awesomplete.d.ts => index.d.ts} | 0 awesomplete/tsconfig.json | 19 +++++ bases/bases-tests.ts | 17 +++-- bases/bases.d.ts | 22 ------ bases/index.d.ts | 20 ++++++ bases/tsconfig.json | 19 +++++ bonjour/bonjour-tests.ts | 1 - bonjour/bonjour.d.ts | 71 ------------------- bonjour/index.d.ts | 68 ++++++++++++++++++ bonjour/tsconfig.json | 19 +++++ chunked-dc/chunked-dc-tests.ts | 2 - chunked-dc/chunked-dc.tscparams | 1 - chunked-dc/{chunked-dc.d.ts => index.d.ts} | 0 chunked-dc/tsconfig.json | 19 +++++ clipboard-js/clipboard-js-tests.ts | 2 - .../{clipboard-js.d.ts => index.d.ts} | 5 +- clipboard-js/tsconfig.json | 19 +++++ ejson/ejson-tests.ts | 6 +- ejson/ejson.d.ts | 26 ------- ejson/index.d.ts | 23 ++++++ ejson/tsconfig.json | 19 +++++ .../{jstimezonedetect.d.ts => index.d.ts} | 0 ldclient-js/{ldclient-js.d.ts => index.d.ts} | 0 ldclient-js/ldclient-js-tests.ts | 4 +- ldclient-js/tsconfig.json | 19 +++++ qrcode/{qrcode.d.ts => index.d.ts} | 0 qrcode/qrcode-tests.ts | 2 - qrcode/tsconfig.json | 19 +++++ quoted-printable/index.d.ts | 25 +++++++ quoted-printable/quoted-printable-tests.ts | 3 - quoted-printable/quoted-printable.d.ts | 27 ------- quoted-printable/tsconfig.json | 19 +++++ react-native-orientation/index.d.ts | 25 +++++++ .../react-native-orientation-tests.ts | 2 - .../react-native-orientation.d.ts | 28 -------- react-native-orientation/tsconfig.json | 19 +++++ request-promise-native/index.d.ts | 31 ++++++++ .../request-promise-native-tests.ts | 2 - .../request-promise-native.d.ts | 35 --------- request-promise-native/tsconfig.json | 19 +++++ sass-graph/{sass-graph.d.ts => index.d.ts} | 5 +- sass-graph/sass-graph-tests.ts | 2 - sass-graph/tsconfig.json | 19 +++++ shopify-buy/{shopify-buy.d.ts => index.d.ts} | 0 shopify-buy/shopify-buy-tests.ts | 3 +- shopify-buy/tsconfig.json | 19 +++++ .../{string-template.d.ts => index.d.ts} | 0 string-template/string-template-tests.ts | 21 +++--- string-template/tsconfig.json | 19 +++++ .../{tesseract.js.d.ts => index.d.ts} | 11 ++- tesseract.js/tesseract.js-tests.ts | 44 ++---------- tesseract.js/tsconfig.json | 19 +++++ timelinejs3/{timelinejs3.d.ts => index.d.ts} | 0 timelinejs3/timelinejs3-tests.ts | 2 - timelinejs3/tsconfig.json | 19 +++++ ...onegap.plugin.istablet.d.ts => index.d.ts} | 0 .../tsconfig.json | 19 +++++ ...kingedge.phonegap.plugin.istablet-tests.ts | 4 +- ...plugin.launchnavigator.d.ts => index.d.ts} | 0 .../tsconfig.json | 19 +++++ ...e.phonegap.plugin.launchnavigator-tests.ts | 4 +- valid-url/index.d.ts | 43 +++++++++++ valid-url/tsconfig.json | 19 +++++ valid-url/valid-url-tests.ts | 2 - valid-url/valid-url.d.ts | 47 ------------ vectorious/{vectorious.d.ts => index.d.ts} | 0 vectorious/tsconfig.json | 19 +++++ vectorious/vectorious-tests.ts | 8 +-- xmlrpc/{xmlrpc.d.ts => index.d.ts} | 2 +- xmlrpc/tsconfig.json | 19 +++++ xmlrpc/xmlrpc-tests.ts | 2 - xtend/index.d.ts | 15 ++++ xtend/tsconfig.json | 19 +++++ xtend/xtend-tests.ts | 1 - xtend/xtend.d.ts | 17 ----- xterm/{xterm.d.ts => index.d.ts} | 9 +-- xterm/tsconfig.json | 19 +++++ xterm/xterm-tests.ts | 2 - 94 files changed, 779 insertions(+), 431 deletions(-) delete mode 100644 async-polling/async-polling.d.ts create mode 100644 async-polling/index.d.ts create mode 100644 async-polling/tsconfig.json rename awesomplete/{awesomplete.d.ts => index.d.ts} (100%) create mode 100644 awesomplete/tsconfig.json delete mode 100644 bases/bases.d.ts create mode 100644 bases/index.d.ts create mode 100644 bases/tsconfig.json delete mode 100644 bonjour/bonjour.d.ts create mode 100644 bonjour/index.d.ts create mode 100644 bonjour/tsconfig.json delete mode 100644 chunked-dc/chunked-dc.tscparams rename chunked-dc/{chunked-dc.d.ts => index.d.ts} (100%) create mode 100644 chunked-dc/tsconfig.json rename clipboard-js/{clipboard-js.d.ts => index.d.ts} (88%) create mode 100644 clipboard-js/tsconfig.json delete mode 100644 ejson/ejson.d.ts create mode 100644 ejson/index.d.ts create mode 100644 ejson/tsconfig.json rename jstimezonedetect/{jstimezonedetect.d.ts => index.d.ts} (100%) rename ldclient-js/{ldclient-js.d.ts => index.d.ts} (100%) create mode 100644 ldclient-js/tsconfig.json rename qrcode/{qrcode.d.ts => index.d.ts} (100%) create mode 100644 qrcode/tsconfig.json create mode 100644 quoted-printable/index.d.ts delete mode 100644 quoted-printable/quoted-printable.d.ts create mode 100644 quoted-printable/tsconfig.json create mode 100644 react-native-orientation/index.d.ts delete mode 100644 react-native-orientation/react-native-orientation.d.ts create mode 100644 react-native-orientation/tsconfig.json create mode 100644 request-promise-native/index.d.ts delete mode 100644 request-promise-native/request-promise-native.d.ts create mode 100644 request-promise-native/tsconfig.json rename sass-graph/{sass-graph.d.ts => index.d.ts} (97%) create mode 100644 sass-graph/tsconfig.json rename shopify-buy/{shopify-buy.d.ts => index.d.ts} (100%) create mode 100644 shopify-buy/tsconfig.json rename string-template/{string-template.d.ts => index.d.ts} (100%) create mode 100644 string-template/tsconfig.json rename tesseract.js/{tesseract.js.d.ts => index.d.ts} (95%) create mode 100644 tesseract.js/tsconfig.json rename timelinejs3/{timelinejs3.d.ts => index.d.ts} (100%) create mode 100644 timelinejs3/tsconfig.json rename uk.co.workingedge.phonegap.plugin.istablet/{uk.co.workingedge.phonegap.plugin.istablet.d.ts => index.d.ts} (100%) create mode 100644 uk.co.workingedge.phonegap.plugin.istablet/tsconfig.json rename uk.co.workingedge.phonegap.plugin.launchnavigator/{uk.co.workingedge.phonegap.plugin.launchnavigator.d.ts => index.d.ts} (100%) create mode 100644 uk.co.workingedge.phonegap.plugin.launchnavigator/tsconfig.json create mode 100644 valid-url/index.d.ts create mode 100644 valid-url/tsconfig.json delete mode 100644 valid-url/valid-url.d.ts rename vectorious/{vectorious.d.ts => index.d.ts} (100%) create mode 100644 vectorious/tsconfig.json rename xmlrpc/{xmlrpc.d.ts => index.d.ts} (98%) create mode 100644 xmlrpc/tsconfig.json create mode 100644 xtend/index.d.ts create mode 100644 xtend/tsconfig.json delete mode 100644 xtend/xtend.d.ts rename xterm/{xterm.d.ts => index.d.ts} (95%) create mode 100644 xterm/tsconfig.json diff --git a/angular-animate/tsconfig.json b/angular-animate/tsconfig.json index 81f1a4a364..a76d9cbdb5 100644 --- a/angular-animate/tsconfig.json +++ b/angular-animate/tsconfig.json @@ -13,6 +13,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-cookies/tsconfig.json b/angular-cookies/tsconfig.json index 81f1a4a364..a76d9cbdb5 100644 --- a/angular-cookies/tsconfig.json +++ b/angular-cookies/tsconfig.json @@ -13,6 +13,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-deferred-bootstrap/tsconfig.json b/angular-deferred-bootstrap/tsconfig.json index aa3c166f61..cd3ad35519 100644 --- a/angular-deferred-bootstrap/tsconfig.json +++ b/angular-deferred-bootstrap/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-mocks/tsconfig.json b/angular-mocks/tsconfig.json index b53af4d397..68a8f53b3c 100644 --- a/angular-mocks/tsconfig.json +++ b/angular-mocks/tsconfig.json @@ -15,6 +15,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-q-spread/tsconfig.json b/angular-q-spread/tsconfig.json index 90110b0e9f..3461eaa2db 100644 --- a/angular-q-spread/tsconfig.json +++ b/angular-q-spread/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-resource/tsconfig.json b/angular-resource/tsconfig.json index fe51bc7293..6bff757b93 100644 --- a/angular-resource/tsconfig.json +++ b/angular-resource/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-route/tsconfig.json b/angular-route/tsconfig.json index 96c224daaf..3301b843a3 100644 --- a/angular-route/tsconfig.json +++ b/angular-route/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-sanitize/tsconfig.json b/angular-sanitize/tsconfig.json index c029bece36..96bc483afb 100644 --- a/angular-sanitize/tsconfig.json +++ b/angular-sanitize/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-websocket/tsconfig.json b/angular-websocket/tsconfig.json index 7579a1591c..a340f7ffbd 100644 --- a/angular-websocket/tsconfig.json +++ b/angular-websocket/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-xeditable/tsconfig.json b/angular-xeditable/tsconfig.json index e9a9c10c51..e81407b730 100644 --- a/angular-xeditable/tsconfig.json +++ b/angular-xeditable/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular/tsconfig.json b/angular/tsconfig.json index ea2099d486..e0d792766a 100644 --- a/angular/tsconfig.json +++ b/angular/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/async-polling/async-polling-tests.ts b/async-polling/async-polling-tests.ts index ec9e5200f2..82adc0299e 100644 --- a/async-polling/async-polling-tests.ts +++ b/async-polling/async-polling-tests.ts @@ -1,6 +1,4 @@ -/// - -import * as AsyncPolling from "async-polling"; +import AsyncPolling = require("async-polling"); // Tests based on examples in https://github.com/cGuille/async-polling#readme diff --git a/async-polling/async-polling.d.ts b/async-polling/async-polling.d.ts deleted file mode 100644 index 579d041e37..0000000000 --- a/async-polling/async-polling.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Type definitions for AsyncPolling -// Project: https://github.com/cGuille/async-polling -// Definitions by: Zlatko Andonovski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "async-polling" { - module AsyncPolling { - export type EventName = "run"|"start"|"error"|"result"|"end"|"schedule"|"stop"; - } - - function AsyncPolling(pollingFunc: (end: (err?: Error, result?: Result) => any) => any, delay: number): { - run: () => any; - stop: () => any; - on: (eventName: AsyncPolling.EventName, listener: Function) => any; - } - - export = AsyncPolling; -} \ No newline at end of file diff --git a/async-polling/index.d.ts b/async-polling/index.d.ts new file mode 100644 index 0000000000..640c863874 --- /dev/null +++ b/async-polling/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for AsyncPolling +// Project: https://github.com/cGuille/async-polling +// Definitions by: Zlatko Andonovski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace AsyncPolling { + export type EventName = "run"|"start"|"error"|"result"|"end"|"schedule"|"stop"; +} + +declare function AsyncPolling(pollingFunc: (end: (err?: Error, result?: Result) => any) => any, delay: number): { + run: () => any; + stop: () => any; + on: (eventName: AsyncPolling.EventName, listener: Function) => any; +} + +export = AsyncPolling; \ No newline at end of file diff --git a/async-polling/tsconfig.json b/async-polling/tsconfig.json new file mode 100644 index 0000000000..0611af7c76 --- /dev/null +++ b/async-polling/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "async-polling-tests.ts" + ] +} \ No newline at end of file diff --git a/awesomplete/awesomplete-tests.ts b/awesomplete/awesomplete-tests.ts index 8132ad4555..11abfdcba0 100644 --- a/awesomplete/awesomplete-tests.ts +++ b/awesomplete/awesomplete-tests.ts @@ -1,5 +1,3 @@ -/// - var input = document.getElementById("myinput"); new Awesomplete(input, {list: "#mylist"}); diff --git a/awesomplete/awesomplete.d.ts b/awesomplete/index.d.ts similarity index 100% rename from awesomplete/awesomplete.d.ts rename to awesomplete/index.d.ts diff --git a/awesomplete/tsconfig.json b/awesomplete/tsconfig.json new file mode 100644 index 0000000000..d76ee637ec --- /dev/null +++ b/awesomplete/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "awesomplete-tests.ts" + ] +} \ No newline at end of file diff --git a/bases/bases-tests.ts b/bases/bases-tests.ts index 5414b18764..85aa71406e 100644 --- a/bases/bases-tests.ts +++ b/bases/bases-tests.ts @@ -1,10 +1,9 @@ -/// import * as bases from 'bases'; - -let bs16String: string = bases.toBase(200, 16); // => 'c8' -let bs62String: string = bases.toBase(99999, 62); // => 'q0T' -let customBaseString: string = bases.toAlphabet(300, 'aAbBcC'); // => 'Abba' - -let frombs16Int: number = bases.fromBase('c8', 16); // => 200 -let frombs62Int: number = bases.fromBase('q0T', 62); // => 99999 -let customBaseInt: number = bases.fromAlphabet('Abba', 'aAbBcC'); // => 300 + +let bs16String: string = bases.toBase(200, 16); // => 'c8' +let bs62String: string = bases.toBase(99999, 62); // => 'q0T' +let customBaseString: string = bases.toAlphabet(300, 'aAbBcC'); // => 'Abba' + +let frombs16Int: number = bases.fromBase('c8', 16); // => 200 +let frombs62Int: number = bases.fromBase('q0T', 62); // => 99999 +let customBaseInt: number = bases.fromAlphabet('Abba', 'aAbBcC'); // => 300 diff --git a/bases/bases.d.ts b/bases/bases.d.ts deleted file mode 100644 index 2e62cf685a..0000000000 --- a/bases/bases.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Type definitions for bases 0.2.1 -// Project: https://github.com/aseemk/bases.js -// Definitions by: Hari Krishna -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "bases" { - export function toAlphabet(num: number, alphabet: string): string; - - export function fromAlphabet(str: string, alphabet: string): number; - - export function toBase(num: number, base: number): string; - - export function fromBase(str: string, base:number): number; - - export let KNOWN_ALPHABETS: any; - - export let NUMERALS: string; - - export let LETTERS_LOWERCASE: string; - - export let LETTERS_UPPERCASE: string; -} diff --git a/bases/index.d.ts b/bases/index.d.ts new file mode 100644 index 0000000000..2111daddf6 --- /dev/null +++ b/bases/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for bases 0.2.1 +// Project: https://github.com/aseemk/bases.js +// Definitions by: Hari Krishna +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function toAlphabet(num: number, alphabet: string): string; + +export function fromAlphabet(str: string, alphabet: string): number; + +export function toBase(num: number, base: number): string; + +export function fromBase(str: string, base:number): number; + +export let KNOWN_ALPHABETS: any; + +export let NUMERALS: string; + +export let LETTERS_LOWERCASE: string; + +export let LETTERS_UPPERCASE: string; diff --git a/bases/tsconfig.json b/bases/tsconfig.json new file mode 100644 index 0000000000..a8df7c46d9 --- /dev/null +++ b/bases/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bases-tests.ts" + ] +} \ No newline at end of file diff --git a/bonjour/bonjour-tests.ts b/bonjour/bonjour-tests.ts index b97794b071..1ae8a218fe 100644 --- a/bonjour/bonjour-tests.ts +++ b/bonjour/bonjour-tests.ts @@ -1,4 +1,3 @@ -/// import * as bonjour from 'bonjour'; var bonjourOptions: bonjour.BonjourOptions; diff --git a/bonjour/bonjour.d.ts b/bonjour/bonjour.d.ts deleted file mode 100644 index 0ffd9f1171..0000000000 --- a/bonjour/bonjour.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Type definitions for bonjour v3.5.0 -// Project: https://github.com/watson/bonjour -// Definitions by: Quentin Lampin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "bonjour" { - export interface BonjourOptions { - multicast?: boolean; - interface?: string; - port?: number; - ip?: string; - ttl?: number; - loopback?: boolean; - reuseAddr?: boolean; - } - - export interface BrowserOptions { - type?: string; - subtypes?: string[]; - protocol?: string; - txt?: Object; - } - - export interface ServiceOptions { - name: string; - host?: string; - port: number; - type: string; - subtypes?: string[]; - protocol?: 'udp'|'tcp'; - txt?: Object; - } - - export interface Service { - name: string; - type: string; - subtypes: string[]; - protocol: string; - host: string; - port: number; - fqdn: string; - rawTxt: Object; - txt: Object; - published: boolean; - - stop: (cb: ()=>any) => void; - start: () => void; - } - - export class Bonjour { - - constructor(opts: BonjourOptions); - publish(options: ServiceOptions):Service; - unpublishAll(cb: ()=>any): void; - find(options:BrowserOptions, onUp: ()=>any): Browser; - findOne(options:any, cb: (service: Service)=>any): Browser; - destroy():void; - } - - export class Browser { - services: Service[]; - - start():void; - update():void; - stop():void; - } - - export function find(options: BrowserOptions, onUp?: ()=>any): Browser; - export function findOne(options: BrowserOptions): Browser; - -} diff --git a/bonjour/index.d.ts b/bonjour/index.d.ts new file mode 100644 index 0000000000..0eb5b584c0 --- /dev/null +++ b/bonjour/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for bonjour v3.5.0 +// Project: https://github.com/watson/bonjour +// Definitions by: Quentin Lampin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface BonjourOptions { + multicast?: boolean; + interface?: string; + port?: number; + ip?: string; + ttl?: number; + loopback?: boolean; + reuseAddr?: boolean; +} + +export interface BrowserOptions { + type?: string; + subtypes?: string[]; + protocol?: string; + txt?: Object; +} + +export interface ServiceOptions { + name: string; + host?: string; + port: number; + type: string; + subtypes?: string[]; + protocol?: 'udp'|'tcp'; + txt?: Object; +} + +export interface Service { + name: string; + type: string; + subtypes: string[]; + protocol: string; + host: string; + port: number; + fqdn: string; + rawTxt: Object; + txt: Object; + published: boolean; + + stop: (cb: ()=>any) => void; + start: () => void; +} + +export class Bonjour { + + constructor(opts: BonjourOptions); + publish(options: ServiceOptions):Service; + unpublishAll(cb: ()=>any): void; + find(options:BrowserOptions, onUp: ()=>any): Browser; + findOne(options:any, cb: (service: Service)=>any): Browser; + destroy():void; +} + +export class Browser { + services: Service[]; + + start():void; + update():void; + stop():void; +} + +export function find(options: BrowserOptions, onUp?: ()=>any): Browser; +export function findOne(options: BrowserOptions): Browser; diff --git a/bonjour/tsconfig.json b/bonjour/tsconfig.json new file mode 100644 index 0000000000..07715bfe01 --- /dev/null +++ b/bonjour/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bonjour-tests.ts" + ] +} \ No newline at end of file diff --git a/chunked-dc/chunked-dc-tests.ts b/chunked-dc/chunked-dc-tests.ts index 304d26e952..8e1ee9f00f 100644 --- a/chunked-dc/chunked-dc-tests.ts +++ b/chunked-dc/chunked-dc-tests.ts @@ -1,5 +1,3 @@ -/// - // Chunker let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2); diff --git a/chunked-dc/chunked-dc.tscparams b/chunked-dc/chunked-dc.tscparams deleted file mode 100644 index ed262d8039..0000000000 --- a/chunked-dc/chunked-dc.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es2015 --noImplicitAny diff --git a/chunked-dc/chunked-dc.d.ts b/chunked-dc/index.d.ts similarity index 100% rename from chunked-dc/chunked-dc.d.ts rename to chunked-dc/index.d.ts diff --git a/chunked-dc/tsconfig.json b/chunked-dc/tsconfig.json new file mode 100644 index 0000000000..d2791d64e6 --- /dev/null +++ b/chunked-dc/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chunked-dc-tests.ts" + ] +} \ No newline at end of file diff --git a/clipboard-js/clipboard-js-tests.ts b/clipboard-js/clipboard-js-tests.ts index 93adfda3a5..ef1bfbdf5d 100644 --- a/clipboard-js/clipboard-js-tests.ts +++ b/clipboard-js/clipboard-js-tests.ts @@ -1,5 +1,3 @@ -/// - clipboard.copy("Hello World"); clipboard.copy(document.body).then(() => console.log("success")); diff --git a/clipboard-js/clipboard-js.d.ts b/clipboard-js/index.d.ts similarity index 88% rename from clipboard-js/clipboard-js.d.ts rename to clipboard-js/index.d.ts index fafc44ef36..8c71b8ed7e 100644 --- a/clipboard-js/clipboard-js.d.ts +++ b/clipboard-js/index.d.ts @@ -13,6 +13,5 @@ declare namespace clipboard { declare var clipboard: clipboard.IClipboardJsStatic; -declare module 'clipboard-js' { - export = clipboard; -} +export = clipboard; +export as namespace clipboard; diff --git a/clipboard-js/tsconfig.json b/clipboard-js/tsconfig.json new file mode 100644 index 0000000000..ffd1667f40 --- /dev/null +++ b/clipboard-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clipboard-js-tests.ts" + ] +} \ No newline at end of file diff --git a/ejson/ejson-tests.ts b/ejson/ejson-tests.ts index ef9b940bb8..1902849b3d 100644 --- a/ejson/ejson-tests.ts +++ b/ejson/ejson-tests.ts @@ -1,8 +1,6 @@ -/// - import { - clone as importedClone, - parse as importedParse, + clone as importedClone, + parse as importedParse, stringify as importedStringify, toJSONValue as importedToJSONValue, fromJSONValue as importedFromJSONValue, diff --git a/ejson/ejson.d.ts b/ejson/ejson.d.ts deleted file mode 100644 index 029222239c..0000000000 --- a/ejson/ejson.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for ejson v2.1.2 -// Project: https://www.npmjs.com/package/ejson -// Definitions by: Shantanu Bhadoria -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare module "ejson" { - interface StringifyOptions { - canonical: boolean; - indent: boolean|number|string; - } - - interface CloneOptions { - keyOrderSensitive: boolean; - } - - function clone(obj: T): T; - function parse(str: string): any; - function stringify(obj: any, options?: StringifyOptions): string; - - function toJSONValue(obj: any): string; - function fromJSONValue(obj: string): any; - function isBinary(value: any): boolean; - function newBinary(len: number): Uint8Array; - function equals(a: any, b: any, options?: CloneOptions): boolean; -} diff --git a/ejson/index.d.ts b/ejson/index.d.ts new file mode 100644 index 0000000000..d2882646eb --- /dev/null +++ b/ejson/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for ejson v2.1.2 +// Project: https://www.npmjs.com/package/ejson +// Definitions by: Shantanu Bhadoria +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface StringifyOptions { + canonical: boolean; + indent: boolean|number|string; +} + +interface CloneOptions { + keyOrderSensitive: boolean; +} + +export function clone(obj: T): T; +export function parse(str: string): any; +export function stringify(obj: any, options?: StringifyOptions): string; + +export function toJSONValue(obj: any): string; +export function fromJSONValue(obj: string): any; +export function isBinary(value: any): boolean; +export function newBinary(len: number): Uint8Array; +export function equals(a: any, b: any, options?: CloneOptions): boolean; diff --git a/ejson/tsconfig.json b/ejson/tsconfig.json new file mode 100644 index 0000000000..45ff41e26b --- /dev/null +++ b/ejson/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ejson-tests.ts" + ] +} \ No newline at end of file diff --git a/jstimezonedetect/jstimezonedetect.d.ts b/jstimezonedetect/index.d.ts similarity index 100% rename from jstimezonedetect/jstimezonedetect.d.ts rename to jstimezonedetect/index.d.ts diff --git a/ldclient-js/ldclient-js.d.ts b/ldclient-js/index.d.ts similarity index 100% rename from ldclient-js/ldclient-js.d.ts rename to ldclient-js/index.d.ts diff --git a/ldclient-js/ldclient-js-tests.ts b/ldclient-js/ldclient-js-tests.ts index cf4ec2b2b6..3b7ea30125 100644 --- a/ldclient-js/ldclient-js-tests.ts +++ b/ldclient-js/ldclient-js-tests.ts @@ -1,5 +1,3 @@ -/// - // Implicitly calls LDClient#identify const ldClient = LDClient.initialize( 'ENV KEY', @@ -27,6 +25,6 @@ function changeCallback(changes: LaunchDarkly.LDFlagChangeset) { ldClient.on('change', changeCallback); -document.getElementById('disable-change-tracking').addEventListener('click', () => { +document.getElementById('disable-change-tracking')!.addEventListener('click', () => { ldClient.off('change', changeCallback); }); diff --git a/ldclient-js/tsconfig.json b/ldclient-js/tsconfig.json new file mode 100644 index 0000000000..37c3af1f5a --- /dev/null +++ b/ldclient-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ldclient-js-tests.ts" + ] +} \ No newline at end of file diff --git a/qrcode/qrcode.d.ts b/qrcode/index.d.ts similarity index 100% rename from qrcode/qrcode.d.ts rename to qrcode/index.d.ts diff --git a/qrcode/qrcode-tests.ts b/qrcode/qrcode-tests.ts index dc1e539a8e..eecfb4a0d1 100644 --- a/qrcode/qrcode-tests.ts +++ b/qrcode/qrcode-tests.ts @@ -1,5 +1,3 @@ -/// - import * as QRCode from 'qrcode'; QRCode.toDataURL('i am a pony!', function (err, url) { diff --git a/qrcode/tsconfig.json b/qrcode/tsconfig.json new file mode 100644 index 0000000000..574c440f00 --- /dev/null +++ b/qrcode/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "qrcode-tests.ts" + ] +} \ No newline at end of file diff --git a/quoted-printable/index.d.ts b/quoted-printable/index.d.ts new file mode 100644 index 0000000000..859c724b38 --- /dev/null +++ b/quoted-printable/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for quoted-printable v0.2.1 +// Project: https://github.com/mathiasbynens/quoted-printable +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * A string representing the semantic version number. + */ +export const version: string; + +/** + * This function takes an encoded byte string (the input + * parameter) and Quoted-Printable-encodes it. Each item + * in the input string represents an octet as per the + * desired character encoding. + */ +export function encode(input: string): string; + +/** + * This function takes a string of text (the text parameter) + * and Quoted-Printable-decodes it. The return value is a + * ‘byte string’, i.e. a string of which each item represents + * an octet as per the character encoding that’s being used. + */ +export function decode(input: string): string; diff --git a/quoted-printable/quoted-printable-tests.ts b/quoted-printable/quoted-printable-tests.ts index c13580bbf9..e720431450 100644 --- a/quoted-printable/quoted-printable-tests.ts +++ b/quoted-printable/quoted-printable-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as quotedPrintable from "quoted-printable"; import * as utf8 from "utf8"; diff --git a/quoted-printable/quoted-printable.d.ts b/quoted-printable/quoted-printable.d.ts deleted file mode 100644 index 2d3edceb0a..0000000000 --- a/quoted-printable/quoted-printable.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Type definitions for quoted-printable v0.2.1 -// Project: https://github.com/mathiasbynens/quoted-printable -// Definitions by: Jeffery Grajkowski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "quoted-printable" { - /** - * A string representing the semantic version number. - */ - export const version: string; - - /** - * This function takes an encoded byte string (the input - * parameter) and Quoted-Printable-encodes it. Each item - * in the input string represents an octet as per the - * desired character encoding. - */ - export function encode(input: string): string; - - /** - * This function takes a string of text (the text parameter) - * and Quoted-Printable-decodes it. The return value is a - * ‘byte string’, i.e. a string of which each item represents - * an octet as per the character encoding that’s being used. - */ - export function decode(input: string): string; -} diff --git a/quoted-printable/tsconfig.json b/quoted-printable/tsconfig.json new file mode 100644 index 0000000000..483bd6b12f --- /dev/null +++ b/quoted-printable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "quoted-printable-tests.ts" + ] +} \ No newline at end of file diff --git a/react-native-orientation/index.d.ts b/react-native-orientation/index.d.ts new file mode 100644 index 0000000000..03139b20dd --- /dev/null +++ b/react-native-orientation/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-native-orientation +// Project: https://github.com/yamill/react-native-orientation +// Definitions by: Moshe Atlow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Orientation { + type orientation = "LANDSCAPE" | "PORTRAIT" | "UNKNOWN" | "PORTRAITUPSIDEDOWN"; + type specificOrientation = "LANDSCAPE-LEFT" | "LANDSCAPE-RIGHT" | "PORTRAIT" | "UNKNOWN" | "PORTRAITUPSIDEDOWN"; + + export function addOrientationListener(callback: (orientation: orientation) => void): void; + export function removeOrientationListener(callback: (orientation: orientation) => void): void; + export function addSpecificOrientationListener(callback: (specificOrientation: specificOrientation) => void): void; + export function removeSpecificOrientationListener(callback: (specificOrientation: specificOrientation) => void): void; + + export function getInitialOrientation(): orientation; + export function lockToPortrait(): void; + export function lockToLandscape(): void; + export function lockToLandscapeLeft(): void; + export function lockToLandscapeRight(): void; + export function unlockAllOrientations(): void; + export function getOrientation(callback: (err: Error, orientation: orientation) => void): void; + export function getSpecificOrientation(callback: (err: Error, orientation: specificOrientation) => void): void; +} + +export = Orientation; diff --git a/react-native-orientation/react-native-orientation-tests.ts b/react-native-orientation/react-native-orientation-tests.ts index 23e3c468c4..66094b4b0a 100644 --- a/react-native-orientation/react-native-orientation-tests.ts +++ b/react-native-orientation/react-native-orientation-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Orientation from 'react-native-orientation'; Orientation.addOrientationListener((orientation)=>{}); diff --git a/react-native-orientation/react-native-orientation.d.ts b/react-native-orientation/react-native-orientation.d.ts deleted file mode 100644 index 1ee7d6f929..0000000000 --- a/react-native-orientation/react-native-orientation.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Type definitions for react-native-orientation -// Project: https://github.com/yamill/react-native-orientation -// Definitions by: Moshe Atlow -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'react-native-orientation' { - - namespace Orientation { - type orientation = "LANDSCAPE" | "PORTRAIT" | "UNKNOWN" | "PORTRAITUPSIDEDOWN"; - type specificOrientation = "LANDSCAPE-LEFT" | "LANDSCAPE-RIGHT" | "PORTRAIT" | "UNKNOWN" | "PORTRAITUPSIDEDOWN"; - - export function addOrientationListener(callback: (orientation: orientation) => void): void; - export function removeOrientationListener(callback: (orientation: orientation) => void): void; - export function addSpecificOrientationListener(callback: (specificOrientation: specificOrientation) => void): void; - export function removeSpecificOrientationListener(callback: (specificOrientation: specificOrientation) => void): void; - - export function getInitialOrientation(): orientation; - export function lockToPortrait(): void; - export function lockToLandscape(): void; - export function lockToLandscapeLeft(): void; - export function lockToLandscapeRight(): void; - export function unlockAllOrientations(): void; - export function getOrientation(callback: (err: Error, orientation: orientation) => void): void; - export function getSpecificOrientation(callback: (err: Error, orientation: specificOrientation) => void): void; - } - - export = Orientation; -} diff --git a/react-native-orientation/tsconfig.json b/react-native-orientation/tsconfig.json new file mode 100644 index 0000000000..074272f98d --- /dev/null +++ b/react-native-orientation/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-orientation-tests.ts" + ] +} \ No newline at end of file diff --git a/request-promise-native/index.d.ts b/request-promise-native/index.d.ts new file mode 100644 index 0000000000..7eadce54aa --- /dev/null +++ b/request-promise-native/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for request-promise-native v1.0.3 +// Project: https://github.com/request/request-promise-native +// Definitions by: Gustavo Henke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import request = require('request'); +import http = require('http'); + +declare namespace requestPromise { + interface RequestPromise extends request.Request { + then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + catch(onrejected?: (reason: any) => any | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; + promise(): Promise; + cancel(): void; + } + + interface RequestPromiseOptions extends request.CoreOptions { + simple?: boolean; + transform?: (body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean) => any; + resolveWithFullResponse?: boolean; + } + + export type OptionsWithUri = request.UriOptions & RequestPromiseOptions; + export type OptionsWithUrl = request.UrlOptions & RequestPromiseOptions; + export type Options = OptionsWithUri | OptionsWithUrl; +} + +declare var requestPromise: request.RequestAPI; +export = requestPromise; diff --git a/request-promise-native/request-promise-native-tests.ts b/request-promise-native/request-promise-native-tests.ts index 7c28ed1017..4267351328 100644 --- a/request-promise-native/request-promise-native-tests.ts +++ b/request-promise-native/request-promise-native-tests.ts @@ -1,5 +1,3 @@ -/// - import * as rp from 'request-promise-native'; rp('http://www.google.com') diff --git a/request-promise-native/request-promise-native.d.ts b/request-promise-native/request-promise-native.d.ts deleted file mode 100644 index 33e847bf6b..0000000000 --- a/request-promise-native/request-promise-native.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Type definitions for request-promise-native v1.0.3 -// Project: https://github.com/request/request-promise-native -// Definitions by: Gustavo Henke -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'request-promise-native' { - import request = require('request'); - import http = require('http'); - - namespace requestPromise { - interface RequestPromise extends request.Request { - then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; - catch(onrejected?: (reason: any) => any | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; - promise(): Promise; - cancel(): void; - } - - interface RequestPromiseOptions extends request.CoreOptions { - simple?: boolean; - transform?: (body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean) => any; - resolveWithFullResponse?: boolean; - } - - export type OptionsWithUri = request.UriOptions & RequestPromiseOptions; - export type OptionsWithUrl = request.UrlOptions & RequestPromiseOptions; - export type Options = OptionsWithUri | OptionsWithUrl; - } - - var requestPromise: request.RequestAPI; - export = requestPromise; -} diff --git a/request-promise-native/tsconfig.json b/request-promise-native/tsconfig.json new file mode 100644 index 0000000000..0edf04e8ec --- /dev/null +++ b/request-promise-native/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "request-promise-native-tests.ts" + ] +} \ No newline at end of file diff --git a/sass-graph/sass-graph.d.ts b/sass-graph/index.d.ts similarity index 97% rename from sass-graph/sass-graph.d.ts rename to sass-graph/index.d.ts index ccc5b45995..26c3d26d20 100644 --- a/sass-graph/sass-graph.d.ts +++ b/sass-graph/index.d.ts @@ -76,6 +76,5 @@ declare namespace SassGraph { export function parseDir(dirpath: string, options?: Options): Graph; } -declare module "sass-graph" { - export = SassGraph; -} +export = SassGraph; +export as namespace SassGraph; diff --git a/sass-graph/sass-graph-tests.ts b/sass-graph/sass-graph-tests.ts index 1e9c65470d..a67154dda5 100644 --- a/sass-graph/sass-graph-tests.ts +++ b/sass-graph/sass-graph-tests.ts @@ -1,5 +1,3 @@ -/// - import { parseFile, parseDir, Graph } from "sass-graph"; // Example copied from readme: diff --git a/sass-graph/tsconfig.json b/sass-graph/tsconfig.json new file mode 100644 index 0000000000..41e6e1bb4c --- /dev/null +++ b/sass-graph/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sass-graph-tests.ts" + ] +} \ No newline at end of file diff --git a/shopify-buy/shopify-buy.d.ts b/shopify-buy/index.d.ts similarity index 100% rename from shopify-buy/shopify-buy.d.ts rename to shopify-buy/index.d.ts diff --git a/shopify-buy/shopify-buy-tests.ts b/shopify-buy/shopify-buy-tests.ts index 3d8d1f5988..58f8e9288f 100644 --- a/shopify-buy/shopify-buy-tests.ts +++ b/shopify-buy/shopify-buy-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// /* Build new ShopifyBuy client ============================================================ */ diff --git a/shopify-buy/tsconfig.json b/shopify-buy/tsconfig.json new file mode 100644 index 0000000000..4b600adf4a --- /dev/null +++ b/shopify-buy/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shopify-buy-tests.ts" + ] +} \ No newline at end of file diff --git a/string-template/string-template.d.ts b/string-template/index.d.ts similarity index 100% rename from string-template/string-template.d.ts rename to string-template/index.d.ts diff --git a/string-template/string-template-tests.ts b/string-template/string-template-tests.ts index 2c9623c3f6..90e852e2f1 100644 --- a/string-template/string-template-tests.ts +++ b/string-template/string-template-tests.ts @@ -1,4 +1,3 @@ -/// import * as format from "string-template"; import * as compile from "string-template/compile"; @@ -6,21 +5,21 @@ import * as compile from "string-template/compile"; namespace format_tests { let greeting: string; - // Format using an object hash with keys matching [0-9a-zA-Z]+ + // Format using an object hash with keys matching [0-9a-zA-Z]+ greeting = format("Hello {name}, you have {count} unread messages", { name: "Robert", count: 12 }) - // greeting -> "Hello Robert, you have 12 unread messages" + // greeting -> "Hello Robert, you have 12 unread messages" - // Format using a number indexed array + // Format using a number indexed array greeting = format("Hello {0}, you have {1} unread messages", ["Robert", 12]) - // greeting -> "Hello Robert, you have 12 unread messages" + // greeting -> "Hello Robert, you have 12 unread messages" - // Format using optional arguments + // Format using optional arguments greeting = format("Hello {0}, you have {1} unread messages", "Robert", 12) - // greeting -> "Hello Robert, you have 12 unread messages" + // greeting -> "Hello Robert, you have 12 unread messages" - // Escape {} pairs by using double {{}} + // Escape {} pairs by using double {{}} let text: string = format("{{0}}") - // text -> "{0}" + // text -> "{0}" } @@ -28,14 +27,14 @@ namespace compile_tests { { let greetingTemplate = compile("Hello {0}, you have {1} unread messages", true) - // -> greetingTemplate generated using new Function + // -> greetingTemplate generated using new Function let greeting = greetingTemplate("Robert", 12) // -> "Hello Robert, you have 12 unread messages" } { let greetingTemplate = compile("Hello {0}, you have {1} unread messages", true) - // -> greetingTemplate generated using new Function + // -> greetingTemplate generated using new Function let greeting = greetingTemplate(["Robert", 12]) // -> "Hello Robert, you have 12 unread messages" diff --git a/string-template/tsconfig.json b/string-template/tsconfig.json new file mode 100644 index 0000000000..e1b4a16335 --- /dev/null +++ b/string-template/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "string-template-tests.ts" + ] +} \ No newline at end of file diff --git a/tesseract.js/tesseract.js.d.ts b/tesseract.js/index.d.ts similarity index 95% rename from tesseract.js/tesseract.js.d.ts rename to tesseract.js/index.d.ts index 0b9457742f..ad0daa2359 100644 --- a/tesseract.js/tesseract.js.d.ts +++ b/tesseract.js/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// -declare module Tesseract { +declare namespace Tesseract { type ImageLike = string | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | CanvasRenderingContext2D | File | Blob | ImageData | Buffer; interface Progress { @@ -141,9 +141,6 @@ declare module Tesseract { } } -declare module "tesseract.js" { - var Tesseract: Tesseract.TesseractStatic - export = Tesseract; -} - declare var Tesseract: Tesseract.TesseractStatic; +export = Tesseract; +export as namespace Tesseract; diff --git a/tesseract.js/tesseract.js-tests.ts b/tesseract.js/tesseract.js-tests.ts index df55b75b3b..7f78a48f96 100644 --- a/tesseract.js/tesseract.js-tests.ts +++ b/tesseract.js/tesseract.js-tests.ts @@ -1,36 +1,4 @@ -/// - -import * as TesseractLib from 'tesseract.js'; - -TesseractLib.recognize("./demo.png", { - lang: 'chi_sim', -}).progress(function (p) { - console.log('progress', p); -}).then(function (result) { - console.log(result.text) -}); - -TesseractLib.detect("./demo.png").then(function (result) { - console.log(result) -}); - -TesseractLib.recognize("./demo.png") - .progress(message => console.log(message)) - .catch(err => console.error(err)) - .then(result => console.log(result)) - .finally(resultOrError => console.log(resultOrError)); - -var job1 = TesseractLib.recognize("./demo.png"); -job1.progress(message => console.log(message)); -job1.catch(err => console.error(err)); -job1.then(result => console.log(result)); -job1.finally(resultOrError => console.log(resultOrError)); - -TesseractLib.create({ - workerPath: '/path/to/worker.js', - langPath: 'https://cdn.rawgit.com/naptha/tessdata/gh-pages/3.02/', - corePath: 'https://cdn.rawgit.com/naptha/tesseract.js-core/0.1.0/index.js', -}); +import * as Tesseract from 'tesseract.js'; Tesseract.recognize("./demo.png", { lang: 'chi_sim', @@ -50,11 +18,11 @@ Tesseract.recognize("./demo.png") .then(result => console.log(result)) .finally(resultOrError => console.log(resultOrError)); -var job2 = Tesseract.recognize("./demo.png"); -job2.progress(message => console.log(message)); -job2.catch(err => console.error(err)); -job2.then(result => console.log(result)); -job2.finally(resultOrError => console.log(resultOrError)); +var job = Tesseract.recognize("./demo.png"); +job.progress(message => console.log(message)); +job.catch(err => console.error(err)); +job.then(result => console.log(result)); +job.finally(resultOrError => console.log(resultOrError)); Tesseract.create({ workerPath: '/path/to/worker.js', diff --git a/tesseract.js/tsconfig.json b/tesseract.js/tsconfig.json new file mode 100644 index 0000000000..ac66d83611 --- /dev/null +++ b/tesseract.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tesseract.js-tests.ts" + ] +} \ No newline at end of file diff --git a/timelinejs3/timelinejs3.d.ts b/timelinejs3/index.d.ts similarity index 100% rename from timelinejs3/timelinejs3.d.ts rename to timelinejs3/index.d.ts diff --git a/timelinejs3/timelinejs3-tests.ts b/timelinejs3/timelinejs3-tests.ts index d5f339de28..b20ad5a62a 100644 --- a/timelinejs3/timelinejs3-tests.ts +++ b/timelinejs3/timelinejs3-tests.ts @@ -1,5 +1,3 @@ -/// - let date1: TL.ITimelineDate = { year: 1999, month: 3, diff --git a/timelinejs3/tsconfig.json b/timelinejs3/tsconfig.json new file mode 100644 index 0000000000..52fb2f54bf --- /dev/null +++ b/timelinejs3/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "timelinejs3-tests.ts" + ] +} \ No newline at end of file diff --git a/uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet.d.ts b/uk.co.workingedge.phonegap.plugin.istablet/index.d.ts similarity index 100% rename from uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet.d.ts rename to uk.co.workingedge.phonegap.plugin.istablet/index.d.ts diff --git a/uk.co.workingedge.phonegap.plugin.istablet/tsconfig.json b/uk.co.workingedge.phonegap.plugin.istablet/tsconfig.json new file mode 100644 index 0000000000..898fac1cd2 --- /dev/null +++ b/uk.co.workingedge.phonegap.plugin.istablet/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "uk.co.workingedge.phonegap.plugin.istablet-tests.ts" + ] +} \ No newline at end of file diff --git a/uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet-tests.ts b/uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet-tests.ts index 04de4a177f..aaaa459224 100644 --- a/uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet-tests.ts +++ b/uk.co.workingedge.phonegap.plugin.istablet/uk.co.workingedge.phonegap.plugin.istablet-tests.ts @@ -1,3 +1 @@ -/// - -console.log("isTablet: "+window.isTablet); +console.log("isTablet: "+window.isTablet); diff --git a/uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator.d.ts b/uk.co.workingedge.phonegap.plugin.launchnavigator/index.d.ts similarity index 100% rename from uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator.d.ts rename to uk.co.workingedge.phonegap.plugin.launchnavigator/index.d.ts diff --git a/uk.co.workingedge.phonegap.plugin.launchnavigator/tsconfig.json b/uk.co.workingedge.phonegap.plugin.launchnavigator/tsconfig.json new file mode 100644 index 0000000000..e2f056296b --- /dev/null +++ b/uk.co.workingedge.phonegap.plugin.launchnavigator/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts" + ] +} \ No newline at end of file diff --git a/uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts b/uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts index 5f551ebac4..46d349cf2d 100644 --- a/uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts +++ b/uk.co.workingedge.phonegap.plugin.launchnavigator/uk.co.workingedge.phonegap.plugin.launchnavigator-tests.ts @@ -1,6 +1,4 @@ -/// - -let app = launchnavigator.APP["GOOGLE_MAPS"]; +let app = launchnavigator.APP["GOOGLE_MAPS"]; let platform = launchnavigator.PLATFORM["ANDROID"]; let destination = "Westminster, London, UK"; diff --git a/valid-url/index.d.ts b/valid-url/index.d.ts new file mode 100644 index 0000000000..c4cc826b7f --- /dev/null +++ b/valid-url/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for valid-url v1.0.9 +// Project: https://github.com/ogt/valid-url +// Definitions by: Steve Hipwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Is the value a well-formed uri? + * Returns the untainted URI if the test value appears to be well-formed. Note that you may really want one of the more practical methods like is_http_uri or is_https_uri, since the URI standard (RFC 3986) allows a lot of things you probably don't want. + * @param {string} value - The potential URI to test. + * @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. + */ +export function isUri(value: any): string; + +/** +* Is the value a well-formed HTTP uri? +* Specialized version of isUri() that only likes http:// urls. As a result, it can also do a much more thorough job validating. Also, unlike isUri() it is more concerned with only allowing real-world URIs through. Things like relative hostnames are allowed by the standards, but probably aren't wise. Conversely, null paths aren't allowed per RFC 2616 (should be '/' instead), but are allowed by this function. +* +* This function only works for fully-qualified URIs. /bob.html won't work. See RFC 3986 for the appropriate method to turn a relative URI into an absolute one given its context. +* +* Note that you probably want to either call this in combo with is_https_uri(). +* i.e. if(isHttpUri(uri) || isHttpsUri(uri)) console.log('Good'); +* or use the convenience method isWebUri which is equivalent. +* @param {string} value - The potential URI to test. +* @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. +*/ +export function isHttpUri(value: any): string; + + +/** +* Is the value a well-formed HTTPS uri? +*See is_http_uri() for details. This version only likes the https URI scheme. Otherwise it's identical to is_http_uri(). +* @param {string} value - The potential URI to test. +* @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. +*/ +export function isHttpsUri(value: any): string; + +/** +* Is the value a well-formed HTTP or HTTPS uri? +* This is just a convenience method that combines isHttpUri and isHttpsUri to accept most common real-world URLs. +* @param {string} value - The potential URI to test. +* @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. +*/ +export function isWebUri(value: any): string; diff --git a/valid-url/tsconfig.json b/valid-url/tsconfig.json new file mode 100644 index 0000000000..4f9515df91 --- /dev/null +++ b/valid-url/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "valid-url-tests.ts" + ] +} \ No newline at end of file diff --git a/valid-url/valid-url-tests.ts b/valid-url/valid-url-tests.ts index b30f17a836..1bb2b2d619 100644 --- a/valid-url/valid-url-tests.ts +++ b/valid-url/valid-url-tests.ts @@ -1,5 +1,3 @@ -/// - import validUrl = require('valid-url'); function testIsUri() { diff --git a/valid-url/valid-url.d.ts b/valid-url/valid-url.d.ts deleted file mode 100644 index 494c872e1e..0000000000 --- a/valid-url/valid-url.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Type definitions for valid-url v1.0.9 -// Project: https://github.com/ogt/valid-url -// Definitions by: Steve Hipwell -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'valid-url' { - - /** - * Is the value a well-formed uri? - * Returns the untainted URI if the test value appears to be well-formed. Note that you may really want one of the more practical methods like is_http_uri or is_https_uri, since the URI standard (RFC 3986) allows a lot of things you probably don't want. - * @param {string} value - The potential URI to test. - * @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. - */ - export function isUri(value: any): string; - - /** - * Is the value a well-formed HTTP uri? - * Specialized version of isUri() that only likes http:// urls. As a result, it can also do a much more thorough job validating. Also, unlike isUri() it is more concerned with only allowing real-world URIs through. Things like relative hostnames are allowed by the standards, but probably aren't wise. Conversely, null paths aren't allowed per RFC 2616 (should be '/' instead), but are allowed by this function. - * - * This function only works for fully-qualified URIs. /bob.html won't work. See RFC 3986 for the appropriate method to turn a relative URI into an absolute one given its context. - * - * Note that you probably want to either call this in combo with is_https_uri(). - * i.e. if(isHttpUri(uri) || isHttpsUri(uri)) console.log('Good'); - * or use the convenience method isWebUri which is equivalent. - * @param {string} value - The potential URI to test. - * @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. - */ - export function isHttpUri(value: any): string; - - - /** - * Is the value a well-formed HTTPS uri? - *See is_http_uri() for details. This version only likes the https URI scheme. Otherwise it's identical to is_http_uri(). - * @param {string} value - The potential URI to test. - * @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. - */ - export function isHttpsUri(value: any): string; - - /** - * Is the value a well-formed HTTP or HTTPS uri? - * This is just a convenience method that combines isHttpUri and isHttpsUri to accept most common real-world URLs. - * @param {string} value - The potential URI to test. - * @returns {string} - The untainted RFC 3986 URI on success, undefined on failure. - */ - export function isWebUri(value: any): string; - -} diff --git a/vectorious/vectorious.d.ts b/vectorious/index.d.ts similarity index 100% rename from vectorious/vectorious.d.ts rename to vectorious/index.d.ts diff --git a/vectorious/tsconfig.json b/vectorious/tsconfig.json new file mode 100644 index 0000000000..534c4da491 --- /dev/null +++ b/vectorious/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vectorious-tests.ts" + ] +} \ No newline at end of file diff --git a/vectorious/vectorious-tests.ts b/vectorious/vectorious-tests.ts index 38c264bc37..1ab8940d93 100644 --- a/vectorious/vectorious-tests.ts +++ b/vectorious/vectorious-tests.ts @@ -1,6 +1,4 @@ -/// - -import { Matrix, Vector } from './vectorious'; +import { Matrix, Vector } from 'vectorious'; let vector: Vector; let num: number; @@ -9,7 +7,7 @@ let str: string; let numberArray: number[]; function testMatrix () { - + const a = new Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]]); const b = new Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]]); @@ -59,7 +57,7 @@ function testMatrix () { } function testVector () { - + const a = new Vector([1, 2, 3]); const b = new Vector([4, 5, 6]); diff --git a/xmlrpc/xmlrpc.d.ts b/xmlrpc/index.d.ts similarity index 98% rename from xmlrpc/xmlrpc.d.ts rename to xmlrpc/index.d.ts index 3e167de970..b962be4324 100644 --- a/xmlrpc/xmlrpc.d.ts +++ b/xmlrpc/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrew Short // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'xmlrpc' { import { EventEmitter } from 'events'; diff --git a/xmlrpc/tsconfig.json b/xmlrpc/tsconfig.json new file mode 100644 index 0000000000..873f195a8a --- /dev/null +++ b/xmlrpc/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xmlrpc-tests.ts" + ] +} \ No newline at end of file diff --git a/xmlrpc/xmlrpc-tests.ts b/xmlrpc/xmlrpc-tests.ts index a31d6a9e5d..a7e8dcffbe 100644 --- a/xmlrpc/xmlrpc-tests.ts +++ b/xmlrpc/xmlrpc-tests.ts @@ -1,5 +1,3 @@ -/// - import * as xmlrpc from 'xmlrpc'; const serverOpts = { diff --git a/xtend/index.d.ts b/xtend/index.d.ts new file mode 100644 index 0000000000..01411defdd --- /dev/null +++ b/xtend/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for xtend 4.0.1 +// Project: https://github.com/Raynos/xtend +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Xtend { + (target: T, source: U): T & U; + (target: T, source1: U, source2: V): T & U & V; + (target: T, source1: U, source2: V, source3: W): T & U & V & W; + (target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; + (target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; + (target: any, ...sources: any[]): any; +} +declare const xtend: Xtend; +export = xtend; diff --git a/xtend/tsconfig.json b/xtend/tsconfig.json new file mode 100644 index 0000000000..61b78981ae --- /dev/null +++ b/xtend/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xtend-tests.ts" + ] +} \ No newline at end of file diff --git a/xtend/xtend-tests.ts b/xtend/xtend-tests.ts index e1ab5b8537..12ad82a1b0 100644 --- a/xtend/xtend-tests.ts +++ b/xtend/xtend-tests.ts @@ -1,4 +1,3 @@ -/// import * as xtend from "xtend"; interface Target { diff --git a/xtend/xtend.d.ts b/xtend/xtend.d.ts deleted file mode 100644 index 616cf81cbd..0000000000 --- a/xtend/xtend.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for xtend 4.0.1 -// Project: https://github.com/Raynos/xtend -// Definitions by: rhysd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "xtend" { - interface Xtend { - (target: T, source: U): T & U; - (target: T, source1: U, source2: V): T & U & V; - (target: T, source1: U, source2: V, source3: W): T & U & V & W; - (target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; - (target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; - (target: any, ...sources: any[]): any; - } - const xtend: Xtend; - export = xtend; -} diff --git a/xterm/xterm.d.ts b/xterm/index.d.ts similarity index 95% rename from xterm/xterm.d.ts rename to xterm/index.d.ts index 33558bd50d..603e8335c1 100644 --- a/xterm/xterm.d.ts +++ b/xterm/index.d.ts @@ -57,7 +57,7 @@ interface XtermConstructor { /** * A terminal options. */ -declare module Xterm { +declare namespace Xterm { interface IOptions { colors?: string[]; @@ -85,8 +85,5 @@ declare module Xterm { declare var Xterm: XtermConstructor; - - -declare module 'xterm' { - export = Xterm; -} +export = Xterm; +export as namespace Xterm; diff --git a/xterm/tsconfig.json b/xterm/tsconfig.json new file mode 100644 index 0000000000..6174d757b6 --- /dev/null +++ b/xterm/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xterm-tests.ts" + ] +} \ No newline at end of file diff --git a/xterm/xterm-tests.ts b/xterm/xterm-tests.ts index 0119ae135e..238cbcc8be 100644 --- a/xterm/xterm-tests.ts +++ b/xterm/xterm-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Terminal from 'xterm'; declare var fetch: any; From f498c98b3bd3ea10cef853f2ce19a28ad0b23aa4 Mon Sep 17 00:00:00 2001 From: Ethan Rubio Date: Sat, 5 Nov 2016 19:11:01 -0700 Subject: [PATCH 062/131] Add string-hash (#12499) Refactor string-hash definition Refactor string-hash to use commonjs --- string-hash/index.d.ts | 8 ++++++++ string-hash/string-hash-tests.ts | 3 +++ string-hash/tsconfig.json | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 string-hash/index.d.ts create mode 100644 string-hash/string-hash-tests.ts create mode 100644 string-hash/tsconfig.json diff --git a/string-hash/index.d.ts b/string-hash/index.d.ts new file mode 100644 index 0000000000..5b8986e05b --- /dev/null +++ b/string-hash/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for string-hash 1.1.1 +// Project: https://github.com/darkskyapp/string-hash +// Definitions by: Ethan Rubio +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function stringHash(str: string): number; + +export = stringHash; diff --git a/string-hash/string-hash-tests.ts b/string-hash/string-hash-tests.ts new file mode 100644 index 0000000000..3723fd87bb --- /dev/null +++ b/string-hash/string-hash-tests.ts @@ -0,0 +1,3 @@ +import hash = require("string-hash"); + +const newHash: number = hash("Mary had a little lamb."); // 1766333550 diff --git a/string-hash/tsconfig.json b/string-hash/tsconfig.json new file mode 100644 index 0000000000..e93748c357 --- /dev/null +++ b/string-hash/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "string-hash-tests.ts" + ] +} \ No newline at end of file From fa723912af2be2a23d732782177965030210e9ab Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sat, 5 Nov 2016 19:12:01 -0700 Subject: [PATCH 063/131] Fix file-saver hyphen (#12507) * Fix folder name for the 'file-saver' package. * Better indentation. --- {filesaver => file-saver}/FileSaver-tests.ts | 0 {filesaver => file-saver}/index.d.ts | 12 ++++++------ {filesaver => file-saver}/tsconfig.json | 0 3 files changed, 6 insertions(+), 6 deletions(-) rename {filesaver => file-saver}/FileSaver-tests.ts (100%) rename {filesaver => file-saver}/index.d.ts (79%) rename {filesaver => file-saver}/tsconfig.json (100%) diff --git a/filesaver/FileSaver-tests.ts b/file-saver/FileSaver-tests.ts similarity index 100% rename from filesaver/FileSaver-tests.ts rename to file-saver/FileSaver-tests.ts diff --git a/filesaver/index.d.ts b/file-saver/index.d.ts similarity index 79% rename from filesaver/index.d.ts rename to file-saver/index.d.ts index 534ce4fe1c..31188a0c7a 100644 --- a/filesaver/index.d.ts +++ b/file-saver/index.d.ts @@ -20,13 +20,13 @@ interface FileSaver { * @summary File name. * @type {DOMString} */ - filename: string, + filename: string, - /** - * @summary Disable Unicode text encoding hints or not. - * @type {boolean} - */ - disableAutoBOM?: boolean + /** + * @summary Disable Unicode text encoding hints or not. + * @type {boolean} + */ + disableAutoBOM?: boolean ): void } diff --git a/filesaver/tsconfig.json b/file-saver/tsconfig.json similarity index 100% rename from filesaver/tsconfig.json rename to file-saver/tsconfig.json From cf9f220044ba46f9841abb9ea860c01e2d00dfdd Mon Sep 17 00:00:00 2001 From: ersimont Date: Sat, 5 Nov 2016 22:17:14 -0400 Subject: [PATCH 064/131] add types for ranginputs (#12506) --- rangyinputs/index.d.ts | 89 ++++++++++++++++++++++++++++++++ rangyinputs/rangyinputs-tests.ts | 23 +++++++++ rangyinputs/tsconfig.json | 19 +++++++ 3 files changed, 131 insertions(+) create mode 100644 rangyinputs/index.d.ts create mode 100644 rangyinputs/rangyinputs-tests.ts create mode 100644 rangyinputs/tsconfig.json diff --git a/rangyinputs/index.d.ts b/rangyinputs/index.d.ts new file mode 100644 index 0000000000..4178b45e7b --- /dev/null +++ b/rangyinputs/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for Rangy Inputs 1.2.0 +// Project: https://github.com/timdown/rangyinputs +// Definitions by: Eric Simonton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare namespace RangyInputs { + interface Selection { + + /** The character index of the start position of the selection */ + start: number; + + /** The character index of the end position of the selection */ + end: number; + + /** The number of characters selected */ + length: number; + + /** The selected Text */ + text: string; + } +} + +interface JQuery { + + /** Note that in IE the textarea or text input must have the focus before calling this method. You can ensure this by calling the focus() method of the element (or its jQuery object). */ + getSelection(): RangyInputs.Selection; + + /** Selects the text within the text input or textarea element between the specified start and end character indices. */ + setSelection(start: number, end?: number): JQuery; + + /** Collapses the selection to an insertion point (caret) either at the start of the current selection if toStart is true or the end of the current selection otherwise. */ + collapseSelection(toStart?: boolean): JQuery; + + /** Deletes the text within the text input or textarea element between the specified start and end character indices and optionally places the caret at the position where the deleted text had been if moveSelection is true. */ + deleteText(start: number, end: number, moveSelection?: boolean): JQuery; + + /** Deletes the currently selected text within the text input or textarea element and places the caret at the position where the deleted text had been. */ + deleteSelectedText(): JQuery; + + /** Deletes the currently selected text within the text input or textarea element, places the caret at the position where the deleted text had been and returns the text that was deleted. */ + extractSelectedText(): string; + + /** + * Inserts the specified text at the specified character position within the text input or textarea element and optionally updates the selection depending on the value of selectionBehaviour. Possible values are: + * + * - "select": Selects the inserted text + * - "collapseToStart": Collapses the selection to a caret at the start of the inserted text + * - "collapseToEnd": Collapses the selection to a caret at the end of the inserted text + * + * If no value is supplied for selectionBehaviour, the selection is not changed and left at the mercy of the browser (placing the caret at the start is not uncommon when the textarea's value is changed). + */ + insertText( + text: string, + pos: number, + selectionBehaviour?: 'select' | 'collapseToStart' | 'collapseToEnd' + ): JQuery; + + /** + * Replaces the currently selected text in the text input or textarea element with the specified text and optionally updates the selection depending on the value of selectionBehaviour. Possible values are: + * + * - "select": Selects the inserted text + * - "collapseToStart": Collapses the selection to a caret at the start of the inserted text + * - "collapseToEnd": Collapses the selection to a caret at the end of the inserted text + * + * If no value is supplied for selectionBehaviour, "collapseToEnd" is assumed. + */ + replaceSelectedText( + text: string, + selectionBehaviour?: 'select' | 'collapseToStart' | 'collapseToEnd' + ): JQuery; + + /** + * Surrounds the currently selected text in the text input or textarea element with the specified pieces of text and optionally updates the selection depending on the value of selectionBehaviour. Possible values are: + * + * - "select": Selects the inserted text + * - "collapseToStart": Collapses the selection to a caret at the start of the inserted text + * - "collapseToEnd": Collapses the selection to a caret at the end of the inserted text + * + * If no value is supplied for selectionBehaviour, "select" is assumed. + */ + surroundSelectedText( + textBefore: string, + textAfter: string, + selectionBehaviour?: 'select' | 'collapseToStart' | 'collapseToEnd' + ): JQuery; +} diff --git a/rangyinputs/rangyinputs-tests.ts b/rangyinputs/rangyinputs-tests.ts new file mode 100644 index 0000000000..cb627d85b1 --- /dev/null +++ b/rangyinputs/rangyinputs-tests.ts @@ -0,0 +1,23 @@ +/// + +let $obj: JQuery = $('meh'); + +let selection: RangyInputs.Selection = $obj.getSelection(); +let start: number = selection.start; +let end: number = selection.end; +let len: number = selection.length; +let text: string = selection.text; +$obj = $obj.setSelection(selection.start) + .setSelection(selection.start, selection.end) + .collapseSelection() + .collapseSelection(true) + .deleteText(0, 3) + .deleteText(0, 3, true) + .deleteSelectedText(); +text = $obj.extractSelectedText(); +$obj.insertText(selection.text, 4) + .insertText(text, 4, 'collapseToStart') + .replaceSelectedText(text) + .replaceSelectedText(text, 'select') + .surroundSelectedText('before', 'after') + .surroundSelectedText('before', 'after', 'collapseToEnd'); diff --git a/rangyinputs/tsconfig.json b/rangyinputs/tsconfig.json new file mode 100644 index 0000000000..e1819e2f04 --- /dev/null +++ b/rangyinputs/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rangyinputs-tests.ts" + ] +} \ No newline at end of file From b469fc9234be1a378b572902d4d9d27e177a8e87 Mon Sep 17 00:00:00 2001 From: Philipp A Date: Sun, 6 Nov 2016 16:17:55 +0100 Subject: [PATCH 065/131] Added copy-webpack-plugin definition (#12508) --- .../copy-webpack-plugin-tests.ts | 72 +++++++++++++++++++ copy-webpack-plugin/index.d.ts | 59 +++++++++++++++ copy-webpack-plugin/tsconfig.json | 19 +++++ 3 files changed, 150 insertions(+) create mode 100644 copy-webpack-plugin/copy-webpack-plugin-tests.ts create mode 100644 copy-webpack-plugin/index.d.ts create mode 100644 copy-webpack-plugin/tsconfig.json diff --git a/copy-webpack-plugin/copy-webpack-plugin-tests.ts b/copy-webpack-plugin/copy-webpack-plugin-tests.ts new file mode 100644 index 0000000000..022a734261 --- /dev/null +++ b/copy-webpack-plugin/copy-webpack-plugin-tests.ts @@ -0,0 +1,72 @@ +import { Configuration } from 'webpack' +import * as CopyWebpackPlugin from 'copy-webpack-plugin' + +const c: Configuration = { + plugins: [ + new CopyWebpackPlugin([ + // {output}/file.txt + { from: 'from/file.txt' }, + + // {output}/to/file.txt + { from: 'from/file.txt', to: 'to/file.txt' }, + + // {output}/to/directory/file.txt + { from: 'from/file.txt', to: 'to/directory' }, + + // Copy directory contents to {output}/ + { from: 'from/directory' }, + + // Copy directory contents to {output}/to/directory/ + { from: 'from/directory', to: 'to/directory' }, + + // Copy glob results to /absolute/path/ + { from: 'from/directory/**/*', to: '/absolute/path' }, + + // Copy glob results (with dot files) to /absolute/path/ + { + from: { + glob:'from/directory/**/*', + dot: true, + }, + to: '/absolute/path' + }, + + // Copy glob results, relative to context + { + context: 'from/directory', + from: '**/*', + to: '/absolute/path' + }, + + // {output}/file/without/extension + { + from: 'path/to/file.txt', + to: 'file/without/extension', + toType: 'file' + }, + + // {output}/directory/with/extension.ext/file.txt + { + from: 'path/to/file.txt', + to: 'directory/with/extension.ext', + toType: 'dir' + }, + ], { + ignore: [ + // Doesn't copy any files with a txt extension + '*.txt', + + // Doesn't copy any file, even if they start with a dot + '**/*', + + // Doesn't copy any file, except if they start with a dot + { glob: '**/*', dot: false } + ], + + // By default, we only copy modified files during + // a watch or webpack-dev-server build. Setting this + // to `true` copies all files. + copyUnmodified: true, + }) + ] +} diff --git a/copy-webpack-plugin/index.d.ts b/copy-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..11a3a30dd9 --- /dev/null +++ b/copy-webpack-plugin/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for copy-webpack-plugin v4.0.0 +// Project: https://github.com/kevlened/copy-webpack-plugin +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack' +import { IOptions } from 'minimatch' + +interface MiniMatchGlob extends IOptions { + glob: string +} + +interface CopyPattern { + /** File source path or glob */ + from: string | MiniMatchGlob + /** + * Path or webpack file-loader patterns. defaults: + * output root if `from` is file or dir. + * resolved glob path if `from` is glob. + */ + to?: string + /** + * How to interpret `to`. defaults: + * 'file' if to has extension or from is file. + * 'dir' if from is directory, to has no extension or ends in '/'. + * 'template' if to contains a template pattern. + */ + toType?: 'file' | 'dir' | 'template' + /** A path that determines how to interpret the `from` path. (default: `compiler.options.context`) */ + context?: string + /** + * Removes all directory references and only copies file names. + * + * If files have the same name, the result is non-deterministic. (default: `false`) + */ + flatten?: boolean + /** Additional globs to ignore for this pattern. (default: `[]`) */ + ignore?: Array + /** Function that modifies file contents before writing to webpack. (default: `(content, path) => content`) */ + transform?: (content: string, path: string) => string + /** Overwrites files already in `compilation.assets` (usually added by other plugins; default: `false`) */ + force?: boolean +} + +interface CopyWebpackPluginConfiguration { + /** Array of globs to ignore. (applied to from; default: `[]`) */ + ignore?: Array + /** Copies files, regardless of modification when using `watch` or `webpack-dev-server`. All files are copied on first build, regardless of this option. (default: `false`) */ + copyUnmodified?: boolean + /** Debug level. warning: only warnings, info/true: file location and read info, debug: very detailed debugging info. (default: `'warning'`) */ + debug?: 'warning' | 'info'|true | 'debug' +} + +interface CopyWebpackPlugin { + new (patterns?: CopyPattern[], options?: CopyWebpackPluginConfiguration): Plugin +} + +declare const copyWebpackPlugin: CopyWebpackPlugin +export = copyWebpackPlugin diff --git a/copy-webpack-plugin/tsconfig.json b/copy-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..1d8d63e8ac --- /dev/null +++ b/copy-webpack-plugin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "copy-webpack-plugin-tests.ts" + ] +} From 3c0d4325272547731b0127e53388f797aa06720a Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Sun, 6 Nov 2016 20:53:30 +0530 Subject: [PATCH 066/131] Add types for lab v11 (#12468) --- lab/index.d.ts | 187 ++++++++++++++++++++++++++++++++++++++++++++++ lab/lab-tests.ts | 169 +++++++++++++++++++++++++++++++++++++++++ lab/tsconfig.json | 19 +++++ 3 files changed, 375 insertions(+) create mode 100644 lab/index.d.ts create mode 100644 lab/lab-tests.ts create mode 100644 lab/tsconfig.json diff --git a/lab/index.d.ts b/lab/index.d.ts new file mode 100644 index 0000000000..2b4c036bde --- /dev/null +++ b/lab/index.d.ts @@ -0,0 +1,187 @@ +// Type definitions for lab 11.1.0 +// Project: https://github.com/hapijs/lab +// Definitions by: Prashant Tiwari +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** The test script. */ +export function script(options?: ScriptOptions): Lab & ExperimentAlt & TestAlt; +/** Access the configured assertion library. */ +export const assertions: any; + +interface Lab { + /** Organise tests into an experiment */ + experiment(desc: string, cb: EmptyCallback): void; + + /** Organise tests into an experiment with options */ + experiment(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** Create a test suite */ + describe(desc: string, cb: EmptyCallback): void; + + /** Create a test suite with options */ + describe(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** Create a test suite */ + suite(desc: string, cb: EmptyCallback): void; + + /** Create a test suite with options */ + suite(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** The test spec */ + test(desc: string, cb: TestCallback): void; + + /** The test spec using a promise */ + test(desc: string, promise: TestPromise): void; + + /** The test spec with options */ + test(desc: string, options: TestOptions, cb: TestCallback): void; + + /** The test spec using a promise with options */ + test(desc: string, options: TestOptions, promise: TestPromise): void; + + /** The test spec */ + it(desc: string, cb: TestCallback): void; + + /** The test spec using a promise */ + it(desc: string, promise: TestPromise): void; + + /** The test spec with options */ + it(desc: string, options: TestOptions, cb: TestCallback): void; + + /** The test spec using a promise with options */ + it(desc: string, options: TestOptions, promise: TestPromise): void; + + /** Perform async actions before the test suite */ + before(cb: AsyncCallback): void; + + /** Perform async actions before the test suite using a promise */ + before(promise: AsyncPromise): void; + + /** Perform async actions before the test suite with options */ + before(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions before the test suite with otions, using a promise */ + before(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions before each test */ + beforeEach(cb: AsyncCallback): void; + + /** Perform async actions before each test using a promise */ + beforeEach(promise: AsyncPromise): void; + + /** Perform async actions before each test with options */ + beforeEach(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions before each test with options, using a promise */ + beforeEach(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions after the test suite */ + after(cb: AsyncCallback): void; + + /** Perform async actions after the test suite using a promise */ + after(promise: AsyncPromise): void; + + /** Perform async actions after the test suite with options */ + after(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions after the test suite with options, using a promise */ + after(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions after each test */ + afterEach(cb: AsyncCallback): void; + + /** Perform async actions after each test using a promise */ + afterEach(promise: AsyncPromise): void; + + /** Perform async actions after each test with options */ + afterEach(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions after each test with options, using a promise */ + afterEach(options: AsyncOptions, promise: AsyncPromise): void; +} + +interface ExperimentAlt { + experiment: SkipOnlyExperiment; + suite: SkipOnlyExperiment; + describe: SkipOnlyExperiment; +} + +interface TestAlt { + test: SkipOnlyTest; + it: SkipOnlyTest; +} + +interface SkipOnlyExperiment { + /** Skip this test suite */ + skip: ExperimentArgs & ExperimentWithOptionsArgs; + + /** Only execute this test suite */ + only: ExperimentArgs & ExperimentWithOptionsArgs; +} + +interface SkipOnlyTest { + /** Skip this test */ + skip: TestArgs & TestWithOptionsArgs; + + /** Only execute this test */ + only: TestArgs & TestWithOptionsArgs; +} + +interface ScriptOptions { + /** Enable auto-execution of the script? (true) */ + schedule?: boolean; + + /** Pass Lab CLI options */ + cli?: any; +} + +interface ExperimentOptions { + /** Set a specific timeout in milliseconds (2000) */ + timeout?: number; + + /** Execute tests in parallel? (false) */ + parallel?: boolean; + + /** Skip execution? (false) */ + skip?: boolean; + + /** Execute only this test/experiment? (false) */ + only?: boolean; +} + +interface TestOptions extends ExperimentOptions { + /** The expected number of assertions to execute */ + plan?: number; +} + +interface AsyncOptions { + /** Set a specific timeout in milliseconds (disabled) */ + timeout?: number; +} + +interface DoneNote { + /** Attach a note to the test case */ + note: (text: string) => void; +} + +type EmptyCallback = () => void; + +type DoneFunction = (err?: Error) => void; + +type CleanupFunction = (func: (next: Function) => void) => void; + +type TestCallback = (done: DoneFunction & DoneNote, onCleanup?: CleanupFunction) => void; + +type TestPromise = () => Promise; + +type AsyncCallback = (done: DoneFunction) => void; + +type AsyncPromise = () => Promise; + +type ExperimentArgs = (desc: string, cb: EmptyCallback) => {}; + +type ExperimentWithOptionsArgs = (desc: string, options: ExperimentOptions, cb: EmptyCallback) => {}; + +type TestArgs = (desc: string, cb: TestCallback) => {}; + +type TestWithOptionsArgs = (desc: string, options: TestOptions, cb: TestCallback) => {} diff --git a/lab/lab-tests.ts b/lab/lab-tests.ts new file mode 100644 index 0000000000..ae77ab242f --- /dev/null +++ b/lab/lab-tests.ts @@ -0,0 +1,169 @@ +import { script, assertions } from "lab"; + +const { experiment, describe, suite, test, it, before, beforeEach, after, afterEach } = script(); +const expect = assertions.expect; +const fail = assertions.fail; + +experiment('math', () => { + + before((done) => { + + setTimeout(() => { + + done(); + }, 1000); + }); + + beforeEach((done) => { + + done(); + }); + + test('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +experiment('math', () => { + + before(() => { + + return Promise.resolve(); + }); + + test('returns true when 1 + 1 equals 2', () => { + + return Promise.resolve() + .then((aValue) => { + + const expectedValue = aValue; + expect(aValue).to.equal(expectedValue); + }); + }); +}); + +experiment.only('with only experiment', () => { + + test('this test will run', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); + + test('another test that will run', (done) => { + + expect(true).to.equal(true); + done(); + }); +}); + +experiment('with only test', () => { + + test.only('only this test will run', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); + + test('another test that will not be executed', (done) => { + + done(); + }); +}); + +test('attaches notes', (done) => { + + expect(1 + 1).to.equal(2); + done.note(`The current time is ${Date.now()}`); + done(); +}); + +test('cleanups after test', (done, onCleanup) => { + + if (onCleanup) { + + onCleanup((next) => { + + return next(); + }); + } + + expect(1 + 1).to.equal(2); + done(); +}); + +experiment('my plan', () => { + + test('only a single assertion executes', { plan: 1 }, (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +experiment('math', { timeout: 1000 }, () => { + + before({ timeout: 500 }, (done) => { + + done(); + }); + + test('returns true when 1 + 1 equals 2', { parallel: true }, (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +describe('math', () => { + + before((done) => { + + done(); + }); + + after((done) => { + + done(); + }); + + afterEach((done) => { + + done(); + }); + + it('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +suite('math', () => { + + test('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +describe('expectation', () => { + + it('should be able to expect', (done) => { + + expect(true).to.be.true(); + + done(); + }); + + it('should be able to fail (This test should fail)', (done) => { + + fail('Should fail'); + + done(); + }); + +}); diff --git a/lab/tsconfig.json b/lab/tsconfig.json new file mode 100644 index 0000000000..5562163523 --- /dev/null +++ b/lab/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lab-tests.ts" + ] +} \ No newline at end of file From 5dedaaa274618bae33ebf248469b8c9dbde99337 Mon Sep 17 00:00:00 2001 From: Fred Eisele Date: Sun, 6 Nov 2016 09:39:54 -0600 Subject: [PATCH 067/131] Webgme types (#12166) * added @types for N3, an RDF package * changed file names to match requirements for syncing with @types * naming recommendation conformance * added type definitions for webgme * provide constructor and factory with same function name * checkpoint * removing declare module n3, making ProperModule * changed reference path to types and corrected errors associated with strict null * checkpoint * test the project with "tsc --project tsconfig.json" * changed from "reference path=" to "reference types=" when possible * removing wildcard declaration * combined *.d.ts files and *-tests.ts * removed task completion comments * removed patch version and strict null check on --- webgme/index.d.ts | 960 +++++++++++++++++++++++++++++++++++++++++ webgme/tsconfig.json | 19 + webgme/webgme-tests.ts | 622 ++++++++++++++++++++++++++ 3 files changed, 1601 insertions(+) create mode 100644 webgme/index.d.ts create mode 100644 webgme/tsconfig.json create mode 100644 webgme/webgme-tests.ts diff --git a/webgme/index.d.ts b/webgme/index.d.ts new file mode 100644 index 0000000000..01a70c73f2 --- /dev/null +++ b/webgme/index.d.ts @@ -0,0 +1,960 @@ +// Type definitions for webgme +// Project: https://webgme.org +// Definitions by: Fred Eisele +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// Based on examination of +// Example: https://github.com/typed-typings/env-node/blob/master/0.12/node.d.ts +// Source: https://raw.githubusercontent.com/phreed/typed-npm-webgme/master/webgme.d.ts +// Documentation: https://editor.webgme.org/docs/source/index.html + +declare module "blob/BlobMetadata" { + export default class BlobMetadata implements Blobs.BlobMetadata { + constructor(); + name: string; + size: number; + mime: string; + context: Common.DataObject; + contentType: string; + } +} + +declare module "plugin/PluginBase" { + export = Core.PluginBase; +} + +declare module "plugin/PluginConfig" { + export = Config.PluginConfig; +} + +declare module "webgme/config/config.default" { + export = Config.config; +} + +declare module "webgme/common" { + export = Common; +} + +declare module "common/util/canon" { + export = Util.CANON; +} + +declare module "common/util/assert" { + export = Util.ASSERT; +} + + +declare namespace Common { + + export type ISO8601 = string; + export type ErrorStr = string; + export type MetadataHash = string; + export type MetadataHashArray = string[]; + export type ArtifactHash = string; + export type Name = string; + + export type Metadata = {} + export class Node { + constructor(); + } + + export type DataObject = {} + export type Buffer = GLbyte[]; + export type Payload = string | Buffer | Buffer[]; + export type Content = DataObject | Buffer | Buffer[]; + export type ContentString = string; + export type Primitive = string | number; + export type OutAttr = DataObject | Primitive | undefined | null; + export type InAttr = DataObject | Primitive | null; + export type OutPath = string | undefined | null; + + export type VoidFn = () => void; + + export type MetadataHashCallback = (err: Error, result: MetadataHash) => void; + export type MetadataHashArrayCallback = (err: Error, result: MetadataHashArray) => void; + export type MetadataCallback = (err: Error, result: Metadata) => void; + export type ObjectCallback = (err: Error, result: DataObject) => void; + export type ObjectArrayCallback = (err: Error, result: DataObject[]) => void; + export type JSONCallback = (err: Error, result: JSON) => void; +} + +declare namespace Util { + + class Canon { + stringify(thing: any): string; + parse(thing: any): string; + } + + export let CANON: Canon; + + export function ASSERT(condition: boolean): never; +} + +declare namespace Blobs { + + export type ObjectBlob = string; + + export interface BlobMetadata { + name: string; + size: number; + mime: string; + context: Common.DataObject; + contentType: string; + } + + export type BlobMetadataDescriptor = {} + + export class BlobClient { + constructor(); + + createArtifact(name: Common.Name): Core.Artifact; + getArtifact: { + (metadataHash: Common.MetadataHash, callback: Core.ArtifactCallback): void; + (metadataHash: Common.MetadataHash): Promise; + } + getMetadataURL(metadataHash: Common.MetadataHash): string; + getRelativeMetadataURL(metadataHash: Common.MetadataHash): string; + getViewURL(metadataHash: Common.MetadataHash, subpath: string): string; + getDownloadURL(metadataHash: Common.MetadataHash, subpath: string): string; + getRelativeDownloadURL(metadataHash: Common.MetadataHash, subpath: string): string; + getCreateURL(filename: Common.Name, isMetadata: boolean): string; + getRelativeCreateURL(filename: Common.Name, isMetadata: boolean): string; + getSubObject: { + (metadataHash: Common.MetadataHash, subpath: string, callback: Common.ObjectCallback): void; + (metadataHash: Common.MetadataHash, subpath: string): Promise; + } + getObject: { + (metadataHash: Common.MetadataHash, callback: Common.ObjectCallback, subpath: string): Common.Content; + (metadataHash: Common.MetadataHash, subpath: string): Promise; + } + getObjectAsString: { + (metadataHash: Common.MetadataHash, callback: Common.MetadataHashCallback): Common.ContentString; + (metadataHash: Common.MetadataHash): Promise; + } + getObjectAsJSON: { + (metadataHash: Common.MetadataHash, callback: Common.JSONCallback): void; + (metadataHash: Common.MetadataHash): Promise; + } + getMetadata: { + (metadataHash: Common.MetadataHash, callback: Common.MetadataCallback): Common.Metadata; + (metadataHash: Common.MetadataHash): Promise; + } + getHumanSize(bytes: number, si: boolean): string; + putFile: { + (name: Common.Name, data: Common.Payload, callback: Common.MetadataHashCallback): void; + (name: Common.Name, data: Common.Payload): Promise; + } + putMetadata: { + (metadataDescriptor: BlobMetadataDescriptor, callback: Common.MetadataHashCallback): void; + (metadataDescriptor: BlobMetadataDescriptor): Promise; + } + putFiles: { + (o: { [name: string]: Common.Payload }, callback: Common.MetadataHashArrayCallback): void; + (o: { [name: string]: Common.Payload }): Promise; + } + saveAllArtifacts: { + (callback: Common.MetadataHashArrayCallback): void; + (): Promise; + } + } + +} + + +/** +Describe plugins +*/ +declare namespace Core { + + export interface ResultCallback { + (err: Error | null, result: Result): void; + } + + export interface Message { + msg: string; + } + + export type ArtifactCallback = (err: Error, result: Artifact) => void; + + export interface Artifact { + name: Common.Name; + blobClient: Blobs.BlobClient; + descriptor: Blobs.BlobMetadata; + + constructor(name: Common.Name, blobClient: Blobs.BlobClient, descriptor: Blobs.BlobMetadata): void; + + /** Adds content to the artifact as a file. */ + addFile: { + (name: Common.Name, content: Blobs.ObjectBlob, callback: Common.MetadataHashCallback): void; + (name: Common.Name, content: Blobs.ObjectBlob): Promise; + } + /** Adds files as soft-link. */ + addFileAsSoftLink: { + (name: Common.Name, content: Blobs.ObjectBlob, callback: Common.MetadataHashCallback): void; + (name: Common.Name, content: Blobs.ObjectBlob): Promise; + } + /** Adds multiple files. */ + addFiles: { + (files: { [name: string]: Blobs.ObjectBlob }, callback: Common.MetadataHashArrayCallback): void; + (files: { [name: string]: Blobs.ObjectBlob }): Promise | Promise; + } + /** Adds multiple files as soft-links. */ + addFilesAsSoftLinks: { + (files: { [name: string]: Blobs.ObjectBlob }, callback: Common.MetadataHashArrayCallback): void; + (files: { [name: string]: Blobs.ObjectBlob }): Promise; + } + /** Adds a metadataHash to the artifact using the given file path. */ + addMetadataHash: { + (name: Common.Name, metadataHash: Common.MetadataHash, size: number, callback: Common.MetadataHashCallback): void; + (name: Common.Name, metadataHash: Common.MetadataHash, size?: number): Promise; + + (objectHashes: { [name: string]: string }, callback: Common.MetadataHashCallback): void; + (objectHashes: { [name: string]: string }): Promise; + } + /** Adds metadataHashes to the artifact using the given file paths. */ + addMetadataHashes: { + (name: Common.Name, metadataHash: Common.MetadataHash, size: number, callback: Common.MetadataHashArrayCallback): void; + (name: Common.Name, metadataHash: Common.MetadataHash, size?: number): Promise; + + (objectHashes: { [name: string]: string }, callback: Common.MetadataHashArrayCallback): void; + (objectHashes: { [name: string]: string }): Promise; + } + /** Adds a metadataHash to the artifact using the given file path. */ + addObjectHash: { + (name: Common.Name, metadataHash: Common.MetadataHash, callback: Common.MetadataHashCallback): void; + (name: Common.Name, metadataHash: Common.MetadataHash): Promise; + } + /** Adds metadataHashes to the artifact using the given file paths. */ + addObjectHashes: { + (objectHashes: { [name: string]: string }, callback: Common.MetadataHashArrayCallback): void; + (objectHashes: { [name: string]: string }): Promise; + } + /** Saves this artifact and uploads the metadata to the server's storage. */ + save: { + (callback: Common.MetadataHashCallback): void; + (message?: string): Promise; + } + } + /** + commitHash - metadataHash of the commit. + status - storage.constants./SYNCED/FORKED/MERGED + */ + export interface Commit { + commitHash: Common.MetadataHash; + status: string; + branchName: string; + } + + export interface Result { + success: boolean; + messages: string[]; // array of PluginMessages + artifacts: Common.ArtifactHash[]; // array of hashes + pluginName: string; + startTime: Date; + finishTime: Date; + error: Error; + projectId: any; + commits: any[]; + + /** + * Gets the success flag of this result object + */ + getSuccess(): boolean; + /** + * Sets the success flag of this result. + */ + setSuccess(value: boolean): void; + /** + * Returns with the plugin messages. + */ + getMessages(): Message[]; + /** + * Adds a new plugin message to the messages list. + */ + addMessage(pluginMessage: Message): void; + /** + * Returns the plugin artifacts. + */ + getArtifacts(): Artifact[]; + /** + * Adds a saved artifact to the result - linked via its metadataHash. + * Takes the metadataHash of saved artifact. + */ + addArtifact(metadataHash: Common.MetadataHash): void; + /** + * Adds a commit to the commit container. + */ + addCommit(commitData: Commit): void; + /** + * Gets the name of the plugin to which the result object belongs. + */ + getPluginName(): string; + //------------------------------------------ + // Methods used by the plugin manager + //----------------------------------------- + /** + * Sets the name of the plugin to which the result object belongs to. + */ + setPluginName(pluginName: string): string; + /** + * Sets the name of the projectId the result was generated from. + */ + setProjectId(projectId: string): void; + /** + * Gets the ISO 8601 representation of the time when the plugin started its execution. + */ + getStartTime(): Common.ISO8601; + /** + * Sets the ISO 8601 representation of the time when the plugin started its execution. + */ + setStartTime(time: Common.ISO8601): void; + /** + * Gets the ISO 8601 representation of the time when the plugin finished its execution. + */ + getFinishTime(): Common.ISO8601; + /** + * Sets the ISO 8601 representation of the time when the plugin finished its execution. + */ + setFinishTime(time: Common.ISO8601): void; + /** + * Gets error if any error occured during execution. + * FIXME: should this return an Error object? + */ + getError(): Common.ErrorStr; + /** + * Sets the error string if any error occured during execution. + */ + setError(error: Common.ErrorStr | Error): void; + /** + * Serializes this object to a JSON representation. + */ + serialize(): { success: boolean, messages: Message[], pluginName: string, finishTime: string }; + } + + + export interface RelationRule { + /** The minimum amount of target necessary for the relationship (if not present or '-1' then there is no minimum rule that applies) */ + min?: number; + /** The maximum amount of target necessary for the relationship (if not present or '-1' then there is no maximum rule that applies) */ + max?: number; + absolutePathOfTarget?: { + min?: number; + max?: number; + } + } + + export interface Constraint { + script: string; + info: string; + priority: string; + } + + export interface MixinViolation { + severity?: string; + type?: string; + ruleName?: string | undefined; + targetInfo?: string | undefined; + targetNode?: Common.Node | undefined; + collisionPaths?: string[]; + collisionNodes?: Common.Node[]; + message?: string; + hint?: string; + } + export interface GmePersisted { rootHash: Common.MetadataHash } + export enum TraversalOrder { 'BFS', 'DFS' } + export type GUID = string; + + export interface NodeParameters { + parent: Common.Node | null; + base: Common.Node | null; + relid?: string; + guid?: GUID; + } + export interface LibraryInfo { + projectId: string; + branchName: string; + commitHash: string; + } + export interface MetaNodeParameters { + object: { node: Common.Node, children: Common.Node[] }; + sensitive: boolean; + multiplicity: boolean; + aspect: string; + } + export interface MetaRule { + type: string | number | boolean; + enum: string[]; + } + + export interface TraversalOptions { + excludeRoot?: boolean; + order?: TraversalOrder; + maxParallelLoad?: number; + stopOnError?: boolean; + } + + export interface Core { + + addLibrary: { + (node: Common.Node, name: Common.Name, libraryRootHash: string, + libraryInfo: LibraryInfo, callback: Common.ObjectCallback): void; + (node: Common.Node, name: Common.Name, libraryRootHash: string, + libraryInfo: LibraryInfo): Promise; + } + addMember(node: Common.Node, name: Common.Name, member: Common.Node): undefined | Error; + addMixin(node: Common.Node, mixinPath: string): undefined | Error; + applyResolution(conflict: {}): {}; + applyTreeDiff: { + (root: Common.Node, patch: Common.DataObject, callback: Common.ObjectCallback): void; + (root: Common.Node, patch: Common.DataObject): Promise; + } + canSetAsMixin(node: Common.Node, mixinPath: string): boolean | string; + clearMetaRules(node: Common.Node): undefined | Error; + clearMixins(node: Common.Node): undefined | Error; + copyNode(node: Common.Node, parent: Common.Node): Common.Node | Error; + copyNodes(nodes: Common.Node[], parent: Common.Node): Common.Node[] | Error; + createNode(parameters: NodeParameters): Common.Node | Error; + createSet(node: Common.Node, name: Common.Name): undefined | Error; + delAspectMeta(node: Common.Node, name: Common.Name): undefined | Error; + delAspectMetaTarget(node: Common.Node, name: Common.Name, targetPath: string): undefined | Error; + delAttribute(node: Common.Node, name: Common.Name): undefined | Error; + delAttributeMeta(node: Common.Node, name: Common.Name): undefined | Error; + delChildMeta(node: Common.Node, childPath: string): undefined | Error; + delConstraint(node: Common.Node, name: Common.Name): undefined | Error; + deleteNode(node: Common.Node): undefined | Error; + deletePointer(node: Common.Node, name: Common.Name): undefined | Error; + deleteSet(node: Common.Node, name: Common.Name): undefined | Error; + delMember(node: Common.Node, name: Common.Name, path: string): undefined | Error; + delMemberAttribute(node: Common.Node, setName: string, memberPath: string, attrName: string): undefined | Error; + delMemberRegistry(node: Common.Node, setName: string, memberPath: string, regName: string): undefined | Error; + delMixin(node: Common.Node, mixinPath: string): undefined | Error; + delPointerMeta(node: Common.Node, name: Common.Name): undefined | Error; + delPointerMetaTarget(node: Common.Node, name: Common.Name, targetPath: string): undefined | Error; + delRegistry(node: Common.Node, name: Common.Name): undefined | Error; + generateTreeDiff: { + (sourceRoot: Common.Node, targetRoot: Common.Node, callBack: Common.ObjectCallback): void; + (sourceRoot: Common.Node, targetRoot: Common.Node): Promise; + } + getAllMetaNodes(node: Common.Node): { [name: string]: Common.Node }; + getAspectMeta(node: Common.Node, name: Common.Name): string[]; + /** + * Retrieves the value of the given attribute of the given node. + * @param node - the node in question. + * @param name - the name of the attribute. + * + * @return The function returns the value of the attribute of the node. + * The retrieved attribute should not be modified as is - it should be copied first! + * The value can be an object or any primitive type. + * If the return value is undefined; the node does not have such attribute defined. + * If the node is undefined the returned value is null. + */ + getAttribute(node: Common.Node | undefined, name: Common.Name): Common.OutAttr; + getAttributeMeta(node: Common.Node, name: Common.Name): {}; + /** Get the defined attribute names */ + getAttributeNames(node: Common.Node): string[]; + /** Get the base node */ + getBase(node: Common.Node): Common.Node; // null + /** Get the base node at the top of the inheritance chain (typically the fco). */ + getBaseRoot(node: Common.Node): Common.Node; + /** Get the most specific meta node. */ + getBaseType(node: Common.Node): Common.Node; // null + getChild(node: Common.Node, relativeId: string): Common.Node; + getChildrenHashes(node: Common.Node): { [name: string]: Common.MetadataHash }; + getChildrenMeta(node: Common.Node): RelationRule; + /** The children paths are available from the node. */ + getChildrenPaths(parent: Common.Node): string[]; + getChildrenRelids(parent: Common.Node): string[]; + getCollectionNames(node: Common.Node): string[]; + getCollectionPaths(node: Common.Node, name: Common.Name): string[]; + getConstraint(node: Common.Node, name: Common.Name): Constraint; // null + getConstraintNames(node: Common.Node): string[]; + getFCO(node: Common.Node): Common.Node; + getFullyQualifiedName(node: Common.Node): string; + getGuid(node: Common.Node): GUID; + getHash(node: Common.Node): Common.MetadataHash; + getJsonMeta(node: Common.Node): {}; + getLibraryGuid(node: Common.Node, name: Common.Name): GUID | Error; + getLibraryInfo(node: Common.Node, name: Common.Name): LibraryInfo; + getLibraryMetaNodes(node: Common.Node, name: Common.Name, onlyOwn?: boolean): Common.Node[]; + getLibraryNames(node: Common.Node): string[]; + getLibraryRoot(node: Common.Node, name: Common.Name): Common.Node; // null + getMemberAttribute(node: Common.Node, setName: string, memberPath: string, attrName: string): Common.OutAttr; + getMemberAttributeNames(node: Common.Node, name: Common.Name, memberPath: string): string[]; + getMemberOwnAttributeNames(node: Common.Node, name: Common.Name, memberPath: string): string[]; + getMemberOwnRegistry(node: Common.Node, name: Common.Name, memberPath: string): string[]; + getMemberPaths(node: Common.Node, name: Common.Name): string[]; + getMemberRegistry(node: Common.Node, setName: string, memberPath: string, regName: string): Common.OutAttr; + getMemberRegistryNames(node: Common.Node, name: Common.Name, memberpath: string): string[]; + getMixinErrors(node: Common.Node): MixinViolation[]; + getMixinNodes(node: Common.Node): { [name: string]: Common.Node }; + getMixinPaths(node: Common.Node): string[]; + getNamespace(node: Common.Node): string; + getOwnAttribute(node: Common.Node, name: Common.Name): Common.OutAttr; + getOwnAttributeNames(node: Common.Node): string[]; + getOwnChildrenPaths(parent: Common.Node): string[]; + getOwnChildrenRelids(parent: Common.Node): string[]; + getOwnConstraintNames(node: Common.Node): string[]; + getOwnJsonMeta(node: Common.Node): Common.DataObject; + getOwnMemberPaths(node: Common.Node, name: Common.Name): string[]; + getOwnMixinNodes(node: Common.Node): { [name: string]: Common.Node }; + getOwnMixinPaths(node: Common.Node): string[]; + getOwnPointerNames(node: Common.Node): string[]; + getOwnPointerPath(node: Common.Node, name: Common.Name): Common.OutPath; + getOwnRegistry(node: Common.Node, name: Common.Name): Common.OutAttr; + getOwnRegistryNames(node: Common.Node): string[]; + getOwnValidAspectNames(node: Common.Node): string[]; + getOwnValidAttributeNames(node: Common.Node): string[]; + /** The parent paths are available from the node. */ + getParent(node: Common.Node): Common.Node; + /** Get the path/id */ + getPath(node: Common.Node): string; + getPointerMeta(node: Common.Node, name: Common.Name): RelationRule; + getPointerNames(node: Common.Node): string[]; + getPointerPath(node: Common.Node, name: Common.Name): Common.OutPath; + /** Get the assigned registry */ + getRegistry(node: Common.Node, name: Common.Name): Common.OutAttr; + /** Get the defined registry names */ + getRegistryNames(node: Common.Node): string[]; + /** Get the relative id */ + getRelid(node: Common.Node): string; + getRoot(node: Common.Node): Common.Node; + getSetNames(node: Common.Node): string[]; + getTypeRoot(node: Common.Node): Common.Node; + getValidAspectNames(node: Common.Node): string[]; + getValidAttributeNames(node: Common.Node): string[]; + getValidChildrenMetaNodes(parameters: MetaNodeParameters): Common.Node[]; + getValidChildrenPaths(node: Common.Node): string[]; + getValidPointerNames(node: Common.Node): string[]; + getValidSetMetaNodes(parameters: MetaNodeParameters): Common.Node[]; + getValidSetNames(node: Common.Node): string[]; + isAbstract(node: Common.Node): boolean; + /** Connections are just nodes with two pointers named "src" and "dst". */ + isConnection(node: Common.Node): boolean; + isEmpty(node: Common.Node): boolean; + isFullyOverriddenMember(node: Common.Node, setName: string, memberPath: string): boolean; + isInstanceOf(node: Common.Node, name: Common.Name): boolean; + isLibraryElement(node: Common.Node): boolean; + isLibraryRoot(node: Common.Node): boolean; + isMemberOf(node: Common.Node): Common.DataObject; + isMetaNode(node: Common.Node): boolean; + isTypeOf(node: Common.Node, type: Common.Node): boolean; + isValidAttributeValueOf(node: Common.Node, name: Common.Name, value: Common.InAttr): boolean; + isValidChildOf(node: Common.Node, parent: Common.Node): boolean; + isValidTargetOf(node: Common.Node, source: Common.Node, name: Common.Name): boolean; + loadByPath: { + (startNode: Common.Node, relativePath: string, callback: Common.ObjectCallback): void; + (startNode: Common.Node, relativePath: string): Promise; + }; + loadChild: { + (parent: Common.Node, relativeId: string, callback: Common.ObjectCallback): void; + (parent: Common.Node, relativeId: string): Promise; + }; + /** Loading the children however requires data that is not (necessarily) available */ + loadChildren: { + (parent: Common.Node, callback: Common.ObjectArrayCallback): void; + (parent: Common.Node): Promise; + } + loadCollection: { + (target: Common.Node, pointerName: string, callback: Common.ObjectCallback): void; + (target: Common.Node, pointerName: string): Promise; + }; + loadOwnSubTree: { + (node: Common.Node, callback: Common.ObjectCallback): void; + (node: Common.Node): Promise; + }; + loadPointer: { + (node: Common.Node, pointerName: string, callback: Common.ObjectCallback): void; + (node: Common.Node, pointerName: string): Promise; + }; + loadRoot: { + (metadataHash: Common.MetadataHash, callback: Common.ObjectCallback): void; + (metadataHash: Common.MetadataHash): Promise; + }; + loadSubTree: { + (node: Common.Node, callback: Common.ObjectCallback): void; + (node: Common.Node): Promise; + }; + loadTree: { + (rootHash: Common.MetadataHash, callback: Common.ObjectCallback): void; + (rootHash: Common.MetadataHash): Promise; + }; + moveNode(node: Common.Node, parent: Common.Node): Common.Node | Error; + persist(node: Common.Node): GmePersisted; + removeLibrary(node: Common.Node, name: Common.Name): void; + renameLibrary(node: Common.Node, oldName: string, newName: string): void; + setAspectMetaTarget(node: Common.Node, name: Common.Name, target: Common.Node): undefined | Error; + setAttribute(node: Common.Node, name: Common.Name, value: Common.InAttr): undefined | Error; + setAttributeMeta(node: Common.Node, name: Common.Name, rule: MetaRule): undefined | Error; + setBase(node: Common.Node, base: Common.Node): undefined | Error; + setChildMeta(node: Common.Node, child: Common.Node, min?: number, max?: number): undefined | Error; + setChildrenMetaLimits(node: Common.Node, min?: number, max?: number): undefined | Error; + setConstraint(node: Common.Node, name: Common.Name, constraint: Constraint): undefined | Error; + setGuid: { + (node: Common.Node, guid: GUID, callback: Common.ObjectCallback): undefined | Error; + (node: Common.Node, guid: GUID): Promise; + }; + setMemberAttribute: { + (node: Common.Node, setName: string, memberPath: string, + SVGPathSegLinetoHorizontalAbsme: string, + value?: Common.InAttr): undefined | Error; + }; + setMemberRegistry(node: Common.Node, setName: string, memberPath: string, regName: string, + value?: Common.InAttr): undefined | Error; + setPointer(node: Common.Node, name: Common.Name, target: Common.Node | null): undefined | Error; + setPointerMetaLimits(node: Common.Node, memberPath: string, + min?: number, max?: number): undefined | Error; + setPointerMetaTarget(node: Common.Node, name: Common.Name, target: Common.Node, min?: number, max?: number): undefined | Error; + /** Get the assigned registry */ + setRegistry(node: Common.Node, name: Common.Name, value: Common.InAttr): undefined | Error; + + /** + * the visitation function will be called for + * every node in the sub-tree, the second parameter of the function + * is a callback that should be called to + * note to the traversal function that the visitation for a given node is finished. + */ + traverse: { + // takes a callback & returning *no* promise + (node: Common.Node, + options: TraversalOptions, + visitFn: (node: Common.Node, finished: Common.VoidFn) => void, + callback: Common.ObjectCallback) + : void; + // takes *no* callback & returns a promise + (node: Common.Node, + options: TraversalOptions, + visitFn: (node: Common.Node, finished: Common.VoidFn) => void) + : Promise; + } + tryToConcatChanges(mine: Common.DataObject, theirs: Common.DataObject): Common.DataObject; + updateLibrary: { + (node: Common.Node, name: Common.Name, libraryRootHash: Common.MetadataHash, + libraryInfo: LibraryInfo, callback: Common.ObjectCallback): void; + (node: Common.Node, name: Common.Name, libraryRootHash: Common.MetadataHash, + libraryInfo: LibraryInfo): Promise; + } + } + + export interface Dictionary { + // allow any number of 'other' properties. + [propName: string]: any; + } + + + /** + Logs debug messages + https://editor.webgme.org/docs/source/global.html#GmeLogger + */ + export interface GmeLogger { + debug(fmt: string, msg?: string | undefined): void; + info(fmt: string, msg?: string | undefined): void; + warn(fmt: string, msg?: string | undefined): void; + error(fmt: string, msg?: string | undefined): void; + /** + Creates a new logger with the same settings + and a name that is an augmentation of this logger and the + provided string. + If the second argument is true + - the provided name will be used as is. + */ + fork(fmt: string, reuse: boolean): GmeLogger; + } + export interface ProjectInterface { + + } + + + export interface ThenCallback { + (): void; + } + export interface CatchCallback { + (err: Error): void; + } + + export interface Promisable { + then(callback: ThenCallback): Promisable; + catch(callback: CatchCallback): Promisable; + } + + /** + The base plugin object from which all plugins should inherit. + */ + export interface Base { + + activeNode: Common.Node; + activeSelection: Common.Node[]; + blobClient: Blobs.BlobClient; + core: Core; + gmeConfig: Config.GmeConfig; + isConfigured: boolean; + logger: GmeLogger; + /** + * The resolved META nodes based on the active namespace. Index by the fully qualified meta node names + * with the namespace stripped off at the start. + * + * For example, if a project has a library A with a library B. If the project and the libraries all have + * two meta nodes named a and b. Depending on the namespace the META will have the following keys: + * + * 1) namespace = '' -> ['a', 'b', 'A.a', 'A.b', 'A.B.a', 'A.B.b'] + * 2) namespace = 'A' -> ['a', 'b', 'B.a', 'B.b'] + * 3) namespace = 'A.B' -> ['a', 'b'] + * + * (N.B. 'a' and 'b' in example 3) are pointing to the meta nodes defined in A.B.) + */ + META: any; + /** + * The namespace the META nodes are coming from (set by invoker). + * The default is the full meta, i.e. the empty string namespace. + * For example, if a project has a library A with a library B. The possible namespaces are: + * '', 'A' and 'A.B'. + */ + namespace: string; + notificationHandlers: any[]; + pluginMetadata: Common.Metadata; + project: ProjectInterface; + result: Result; + rootNode: Common.Node; + + addCommitToResult(status: string): void; + baseIsMeta(node: any): boolean; + + configure(config: Config.GmeConfig): void; + createMessage(node: any, message: string, serverity: string): void; + /** + * Gets the configuration structure for the plugin. + * The ConfigurationStructure defines the configuration for the plugin + * and will be used to populate the GUI when invoking the plugin from webGME. + */ + getConfigStructure(): Config.ConfigItem[]; + getCurrentConfig(): Config.GmeConfig; + getDefaultConfig(): Config.GmeConfig; + /** + * Gets the description of the plugin. + */ + getDescription(): string; + getMetadata(): any; + getMetaType(node: any): any; + /** + * Gets the name of the plugin. + */ + getName(): string; + /** + * Gets the semantic version (semver.org) of the plugin. + */ + getVersion(): string; + initialize(logger: GmeLogger, blobClient: Blobs.BlobClient, gmeConfig: Config.GmeConfig): void; + isInvalidActiveNode(pluginId: any): any; + isMetaTypeOf(node: any, metaNode: any): boolean; + /** + Main function for the plugin to execute. + Notes: + - Always log with the provided logger.[error,warning,info,debug]. + - Do NOT put any user interaction logic UI, etc. inside this method. + - handler always has to be called even if error happened. + + When this runs the core api is used to extract the essential + meta-model and the model-instance, these are then written to the mega-model. + The mega-model contains all of the models used to describe the target system. + + https://github.com/ptaoussanis/sente + and https://github.com/cognitect/transit-format + will be used to connect to the + graph database (immortals) where the mega-model is stored. + + @param {function(string, plugin.PluginResult)} handler - the result handler + */ + main(callback: ResultCallback): void; + save(message?: string): Promisable; // returns a promise? + sendNotification: { + (message: string, callback: Common.ObjectCallback): void; + (message: string): Promise; + } + setCurrentConfig(newConfig: Config.GmeConfig): void; + updateMeta(generatedMeta: any): void; + updateSuccess(value: boolean, message: TemplateStringsArray): void; + } + + class PluginBase implements Base { + constructor(); + + activeNode: Common.Node; + activeSelection: Common.Node[]; + blobClient: Blobs.BlobClient; + core: Core.Core; + gmeConfig: Config.GmeConfig; + isConfigured: boolean; + logger: Core.GmeLogger; + META: any; + namespace: string; + notificationHandlers: any[]; + pluginMetadata: Common.Metadata; + project: Core.ProjectInterface; + result: Core.Result; + rootNode: Common.Node; + + addCommitToResult(status: string): void; + baseIsMeta(node: any): boolean; + configure(config: Config.GmeConfig): void; + createMessage(node: any, message: string, serverity: string): void; + getConfigStructure(): any; + getCurrentConfig(): Config.GmeConfig; + getDefaultConfig(): Config.GmeConfig; + getDescription(): string; + getMetadata(): any; + getMetaType(node: any): any; + getName(): string; + getVersion(): string; + initialize(logger: GmeLogger, blobClient: Blobs.BlobClient, gmeConfig: Config.GmeConfig): void; + isInvalidActiveNode(pluginId: any): any; + isMetaTypeOf(node: any, metaNode: any): boolean; + main(callback: Core.ResultCallback): void; + save(message?: string): Core.Promisable; + sendNotification: { + (message: string, callback: Core.ResultCallback): void; + (message: string): Promise; + } + setCurrentConfig(newConfig: Config.GmeConfig): void; + updateMeta(generatedMeta: any): void; + updateSuccess(value: boolean, message: TemplateStringsArray): void; + } + +} + +/** + * Each Plugin has a configuration specified via a metadata.json file. + * This interface prescribes that configuration file. + * + */ +declare namespace Config { + + type StringDictionary = { [key: string]: string }; + + export interface ConfigItem { + // a unique name for the configuration item + name: Common.Name; + // a human comprehensible name + displayName: string; + // a detailed description fo the item + description: string; + // the value of the item: if valueItem is provided it must be one of those values. + value: string; + // the datatype of the value: 'string', 'integer', ... + valueType: string, + // an enumeration of the allowed values for the value field + valueItems?: string[]; + // a regular expression limiting the values allowed. + // e.g. '^[a-zA-Z]+$' + regex?: RegExp; + // a description of the regex grammar + // e.g. 'Name can only contain English characters!' + regexMessage?: string; + // can the value be changed? + readOnly?: boolean; + } + + + /** + https://editor.webgme.org/docs/source/global.html#GmeConfig + https://github.com/webgme/webgme/blob/master/config/README.md + */ + export class GmeConfig { + constructor(); + /** Add-on related settings. */ + addOns: any; + /** Authentication related settings. */ + authentication: { + enable: boolean, + jwt: { privateKey: string, publicKey: string }, + logInUrl: string, + logOutUrl: string + }; + /** Bin script related settings. */ + bin: any; + /** Blob related settings. */ + blob: Blobs.ObjectBlob; + /** Client related settings. */ + client: { log: { level: string } }; + /** Client related settings. */ + core: Core.Core; + /** Enables debug mode. */ + public debug: boolean; + /** Executor related settings. */ + executor: any; + /** Mongo database related settings. */ + mongo: { uri: string }; + /** Plugin related settings. */ + plugin: { + basePaths: string[], + allowBrowserExecution: boolean, + allowServerExecution: boolean + }; + /** Additional paths to for requirejs. */ + requirejsPaths: StringDictionary; + /** REST related settings. */ + rest: any; + /** Seed related settings. */ + seedProjects: { + basePaths: string[], + panelPaths: string[], + enable: boolean, + allowDuplication: boolean + }; + /** Server related settings. */ + server: { + port: number, handle: { fd: number }, + log: any + }; + /** Socket IO related settings. */ + socketIO: any; + /** Storage related settings. */ + storage: any; + /** Visualization related settings. */ + visualization: { + panelPaths: string[], + visualizerDescriptors: string[], + extraCss: string[] + }; + + serialize(): any; + } + + + export class PluginConfig extends Config.GmeConfig { + [propName: string]: any; + } + + export let config: PluginConfig; + +} + +/** +Things in this module are deprecated. +This was a serialization supported in version 1. +*/ +declare module "webgme/v1" { + export type GUID = string; + + export interface JsonContainment { + [index: string]: JsonContainment; + } + export interface JsonNode { + attributes: any; + base: string; + meta: any; + parent: string; + pointers: any; + registry: any; + sets: any; + constratints: any; + } + export interface JsonObj { + root: { path: string; guid: GUID }; + containment: JsonContainment; // guid tree of hashes + bases: any; // + nodes: any; + relids: any; + metaSheets: any; + } +} \ No newline at end of file diff --git a/webgme/tsconfig.json b/webgme/tsconfig.json new file mode 100644 index 0000000000..17039ce0e4 --- /dev/null +++ b/webgme/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "webgme-tests.ts" + ] +} \ No newline at end of file diff --git a/webgme/webgme-tests.ts b/webgme/webgme-tests.ts new file mode 100644 index 0000000000..d009e936e4 --- /dev/null +++ b/webgme/webgme-tests.ts @@ -0,0 +1,622 @@ + +/// +/// + +/** + * In actual usage the MetaDataStr would most likely + * be initialized with an import... + * + import MetaDataStr = require("text!metadata.json"); + * + * Which would require a declaration, like... + * `text.d.ts` + * + declare module "text!*" { + var text: string; + export = text; + } + * + */ +const MetaDataStr = ""; + +import Promise = require("bluebird"); +import PluginBase = require("plugin/PluginBase"); + +import * as fs from "fs"; +import * as stream from "stream"; +import * as Common from "webgme/common"; + +/** + * The following items are not created directly by the + * plugin driver. + * + * self is an instance of the PluginBase class. + */ +let self = new PluginBase(); +let node = new Common.Node(); +let connNode = new Common.Node(); +let sourceNode = new Common.Node(); +let destinationNode = new Common.Node(); + +/** + * These tests are derived from... + * https://github.com/webgme/webgme/wiki/GME-Core-API + * + * Nearly all core functions takes a CoreNode as its first argument. + * When using the Core API externally each CoreNode corresponds + * to one node/model in the project tree. + * To access data from the node the Core API should be used + * and the properties on the CoreNode itself should + * not be accessed or modified directly. + * + * Below follows a handpicked selection of basic core functions. + */ + +/** + * https://github.com/webgme/webgme/wiki/GME-Core-API#common-properties + */ +function test_core_common_properties() { + let path = self.core.getPath(node); + let relid = self.core.getRelid(node); + let guid = self.core.getGuid(node); +} + +/** +https://github.com/webgme/webgme/wiki/GME-Core-API#attributes +*/ +function test_core_attributes() { + let name = self.core.getAttribute(node, 'name'); + self.core.setAttribute(node, 'name', 'newName'); + let attributeNames = self.core.getAttributeNames(node); +} + +/** +https://github.com/webgme/webgme/wiki/GME-Core-API#registries +*/ +function test_core_registries() { + let position = self.core.getRegistry(node, 'position'); + self.core.setRegistry(node, 'position', { x: 100, y: 100 }); + let registryNames = self.core.getRegistryNames(node); +} + +/** + * https://github.com/webgme/webgme/wiki/GME-Core-API#inheritance + */ +function test_core_inheritance() { + let baseNode = self.core.getBase(node); + let fcoNode = self.core.getBaseRoot(node); + let aMetaNode = self.core.getBaseType(node); +} + +/** + * https://github.com/webgme/webgme/wiki/GME-Core-API#the-traverse-method + */ +function test_core_containment_traversal() { + function atNode(node: Common.Node, done: Common.VoidFn) { + let metaNode = self.core.getBaseType(node); + let nodeName = self.core.getAttribute(node, 'name'); + // Library-roots do not have a meta-type either. + let metaName = metaNode ? self.core.getAttribute(metaNode, 'name') : ':LibraryRoot:'; + + console.log(`${nodeName} at ${self.core.getPath(node)} is of meta type ${metaName}`); + done(); + } + // Traversal from the root-node (itself will be excluded since it doesn't have a meta-type). + self.core.traverse(self.rootNode, { excludeRoot: true }, atNode, (err): void => { + if (err) { + // Something went wrong! + // Handle the error and return. + } + // At this point we have successfully visited all nodes. + }); +} + +/** + * https://github.com/webgme/webgme/wiki/GME-Core-API#containment-methods + */ +function test_core_containment_methods() { + let childrenPaths = self.core.getChildrenPaths(node); + let parentNode = self.core.getParent(node); + let baseNode = self.core.getBase(node); + let rootNode = self.core.getRoot; + + // Loading the children however requires data that is not (necessarily) available + self.core.loadChildren(node, (err, children) => { + if (err) { + // Something went wrong! + // Handle the error and return. + } + // We have an array of the children and can get information from them. + for (let child of children) { + console.log(self.core.getAttribute(child, 'name')); + } + }); + // This line will be hit before the callback of loadChildren + + // Create a new node, the new node is available directly. + let params = { + parent: parentNode, + base: baseNode + }; + + var newNode = self.core.createNode(params); + + // Copy a node. + var copiedNode = self.core.copyNode(node, parentNode); + + // Delete a node. + self.core.deleteNode(newNode); + + // Loading nodes by paths + // N.B. the path provided is relative the node in the first argument, + // here the root-node is passed to the path is the absolute (i.e. same + // as self.core.getPath(someNode);) + self.core.loadByPath(rootNode, '/1', (err, node) => { + if (err) { + // Handle error + } + // Here we have access to the node. + }); + + // Loading an entire sub-tree of nodes + // N.B. this requires all nodes to be loaded at the same time. + // For larger models core.traverse is preferred. + self.core.loadSubTree(node, (err, nodes) => { + if (err) { + // Handle error + } + // Here we have access to all the nodes that is contained in node + // at any level. + }); +} + +/** + * https://github.com/webgme/webgme/wiki/GME-Core-API#pointers-and-connections + */ + +function test_core_pointers_connections() { + + // + let isConn = self.core.isConnection(connNode); + + // Get the path of the node that is pointed to, via 'src', from connNode. + // (Here the paths to the source node of the connection.) + var sourceNodePath = self.core.getPointerPath(connNode, 'src'); + + // Load the node node that is pointed to, via 'src', from connNode. + // (Here the source node of the connection.) + self.core.loadPointer(connNode, 'src', (err, sourceNode) => { + if (err) { + // Handle error + } + // Here we have access to the sourceNode. + }); + + // Get the paths of the nodes with pointers named 'src' to the sourceNode. + // (Here the paths to the connections that have sourceNode as source.) + let connectionPaths = self.core.getCollectionPaths(sourceNode, 'src'); + + // Load the nodes with pointers named 'src' to the sourceNode. + // (Here the connections that have sourceNode as source.) + self.core.loadCollection(sourceNode, 'src', (err, connNodes) => { + if (err) { + // Handle error + } + // connNodes is an array (a node can have multiple connections/pointers) + // connNode above is within connNodes. + }); + + // Creating new pointers. + // (Since we create both the 'src' and 'dst' this will be rendered as a connection between the two nodes.) + self.core.setPointer(connNode, 'src', sourceNode); + self.core.setPointer(connNode, 'dst', destinationNode); +} + + +/** + * https://github.com/webgme/webgme/wiki/GME-Blob-Storage-API + * + * File-like objects/artifacts + * (which are neither a meta archetype model, nor an instance model) + * are stored separately from the WebGME meta-models and models. + * An example of such an artifact would be a resource + * file that is associated with a model + * (e.g., data for an instance model, or a generated artifact from analyzing a model). + * + * One reason for treating these objects differently is that they do not conform to the data model, + * and they might not be well-suited for storage in a database + * (the Blob is suited to handle binary objects of any size and structure). + */ + +/** + * https://github.com/webgme/webgme/wiki/GME-Blob-Storage-API#usage + */ +function test_client_creating_an_instance() { + // let client = new GME.classes.Client(GME.gmeConfig); +} + +/** + * Add the remaining tests. + */ + + +/** + * https://github.com/webgme/webgme/wiki/GME-Blob-Storage-API + * + * File-like objects/artifacts + * (which are neither a meta archetype model, nor an instance model) + * are stored separately from the WebGME meta-models and models. + * An example of such an artifact would be a resource + * file that is associated with a model + * (e.g., data for an instance model, or a generated artifact from analyzing a model). + * + * One reason for treating these objects differently is that they do not conform to the data model, + * and they might not be well-suited for storage in a database + * (the Blob is suited to handle binary objects of any size and structure). + */ + + + +/** + * The following items are not created directly by the + * plugin driver. + * + * self is an instance of the PluginBase class. + */ + +interface DataModel { + stateMachine: { + name: string, + initialState: string | null, + finalStates: any[], states: any[] + } +}; + +/** + * https://github.com/webgme/webgme/wiki/GME-Blob-Storage-API#usage + */ +function test_client_using_a_blob() { + + class SamplePlugin extends PluginBase { + pluginMetadata: any; + private dataModel: DataModel; + + constructor() { + super(); + this.pluginMetadata = JSON.parse(MetaDataStr); + } + + extractDataModel(): DataModel { + return { stateMachine: { name: "dm", initialState: null, finalStates: [], states: [] } }; + } + + public main(mainHandler: Core.ResultCallback): void { + let artifact: Core.Artifact; + + Promise + .try(() => { + return this.extractDataModel(); + }) + .then((dataModel) => { + var dataModelStr = JSON.stringify(dataModel, null, 4); + this.dataModel = dataModel; + + this.logger.info('Extracted dataModel', dataModelStr); + + return self.blobClient.putFile('dataModel.json', dataModelStr); + }) + .then((jsonFileHash) => { + // Add link from result to this file. + self.result.addArtifact(jsonFileHash); + + // Create a complex artifact, with links to multiple files. + artifact = self.blobClient.createArtifact('simulator'); + + let programJS = "some javascript file"; + self.logger.info('program.js', programJS); + + return artifact.addFilesAsSoftLinks({ + 'program.js': programJS, + 'index.html': this.pluginMetadata + }); + }) + } + } +} + +/** + * Add the remaining tests. + */ + +/** + * This is an extract from a Darpa project. + */ + + +type DictionaryAny = { [key: string]: any }; + +/** +* Visit the node and perform the function. +* Related example using traverse. +* https://github.com/webgme/xmi-tools/blob/master/src/plugins/XMIExporter/XMIExporter.js#L430 +*/ +function test_core_containment_traversal_complete() { + const BLANK = ""; + const NULL_OBJECT = "_OBJECT" + const NULL_GUID = "00000000-0000-0000-0000-000000000000"; + + function getEdgesModel(sponsor: PluginBase, core: Core.Core, + _rootNode: Common.Node, _metaNode: Common.Node): Core.Dictionary { + + let fcoName = core.getAttribute(core.getFCO(sponsor.rootNode), "name"); + let languageName = core.getAttribute(sponsor.rootNode, "name"); + sponsor.logger.info(`get model edges : ${languageName} : ${fcoName}`); + + let rootEntry + = { + "version": "0.0.1", + "pointers": {}, "inv_pointers": {}, + "sets": {}, "inv_sets": {}, + "base": { + "name": NULL_OBJECT, + "guid": NULL_GUID, + }, + "name": { + "name": NULL_OBJECT, "uriExt": BLANK, "uriPrefix": BLANK, + "uriName": BLANK, "uriGen": BLANK + }, + "type": { + "domain": languageName, + "meta": NULL_GUID, "root": NULL_GUID, "base": NULL_GUID, "parent": NULL_GUID + }, + "attributes": {}, + "children": {}, + "guid": NULL_GUID + }; + let nodeGuidMap: Core.Dictionary = { + [NULL_GUID]: rootEntry + }; + + sponsor.logger.info("A dictionary: look up nodes based on their path name."); + let path2entry: Core.Dictionary = { [BLANK]: rootEntry }; + + /** + * A filter mechanism to effectively eliminate containment branches. + * Any path included in the prune-list will be the root of a + * pruned subtree. + */ + let pruneList: string[] = []; + + /** + * The base node makes reference to inheritance. + * The parent node makes reference to containment. + * The traverse function follows the containment tree. + * @type {[type]} + */ + let visitFn = (node: Node, done: Common.VoidFn): void => { + try { + let core = sponsor.core; + let nodePath: string = core.getPath(node); + + let prunedRootPath: string | null = null; + for (let pl of pruneList) { + if (nodePath.indexOf(pl) !== 0) { continue; } + // console.log(`pruned: ${nodePath}::${pl}`); + prunedRootPath = pl; + } + + let nodeNameAttr = core.getAttribute(node, "name"); + if (typeof nodeNameAttr !== "string") { return; } + + // sponsor.logger.info(`visitor function with ${nodeNameAttr}`); + + let baseNodeGuid: string = core.getGuid(core.getBase(node)); + let baseNodeTypeGuid: string = core.getGuid(core.getBaseType(node)); + let baseNodeRootGuid: string = core.getGuid(core.getBaseRoot(node)); + + // set the nodes sourceGuid + let sourceGuid: string = core.getGuid(node); + let sourceEntry + = { + "guid": sourceGuid, + "name": {}, + "type": { + "domain": languageName, + "meta": baseNodeTypeGuid, + "root": baseNodeRootGuid, + "base": baseNodeGuid + }, + "pointers": {}, "inv_pointers": {}, + "sets": {}, "inv_sets": {}, + "base": { + "name": NULL_OBJECT, + "guid": NULL_GUID + }, + "attributes": {}, + "children": {} + }; + nodeGuidMap[sourceGuid] = sourceEntry; + + let metaName: string; + let metaNodeGuid: string; + if (node === sponsor.rootNode) { + metaName = ":Root:"; + sourceEntry.type = { + "domain": BLANK, + "meta": NULL_GUID, + "root": NULL_GUID, + "base": NULL_GUID + }; + metaNodeGuid = NULL_GUID; + } else if (core.isLibraryRoot(node)) { + metaName = ":LibraryRoot:"; + metaNodeGuid = core.getGuid(node); + + // console.log(`prune: ${nodePath}`); + pruneList.push(nodePath); + prunedRootPath = nodePath; + } else { + let metaNameAttr = core.getAttribute(core.getBaseType(node), "name"); + if (typeof metaNameAttr !== "string") { return; } + metaName = metaNameAttr; + metaNodeGuid = core.getGuid(core.getParent(node)); + } + let containRel = metaName; + path2entry[nodePath] = sourceEntry; + + // set the parent to know its child the root node has no parent + // if a non-pruned item has a pruned parent then bring it in. + if (node !== sponsor.rootNode) { + let parent: Common.Node = core.getParent(node); + let parentPath: string = core.getPath(parent); + + let parentData = path2entry[parentPath]; + let children = parentData.children; + children[containRel] = children[containRel] || []; + // children[containRel].push(sourceEntry); + children[containRel].push(sourceGuid); + } + + // set the nodes attributes + core.getAttributeNames(node).forEach((attrName: string) => { + let attrValueRaw = core.getAttribute(node, attrName); + let attrValue: string; + if (typeof attrValueRaw === "string") { + attrValue = attrValueRaw; + } else { + attrValue = ""; + } + let sen = sourceEntry.name; + }); + + // get pointers & inv_pointers + Promise + .try(() => { + return core.getPointerNames(node); + }) + .map((ptrName: string) => { + let targetPathRaw = core.getPointerPath(node, ptrName); + if (typeof targetPathRaw !== "string") { return; } + + let targetPath: string = targetPathRaw; + Promise + .try(() => { + return core.loadByPath(sponsor.rootNode, targetPath); + }) + .then((targetNode: Node) => { + let targetGuid = core.getGuid(targetNode); + if (ptrName === "base") { + + } else { + let pointers: DictionaryAny = sourceEntry.pointers; + let targetMetaNode = core.getBaseType(targetNode); + let targetMetaName = core.getAttribute(targetMetaNode, "name"); + if (typeof targetMetaName === "string") { + pointers[ptrName] = { + name: targetMetaName, + guid: targetGuid + }; + } + let targetEntry = nodeGuidMap[targetGuid]; + if (targetEntry === undefined) { + targetEntry = { + "name": {}, + "guid": targetGuid, + "pointers": {}, "inv_pointers": {}, + "sets": {}, "inv_sets": {} + }; + nodeGuidMap[targetGuid] = targetEntry; + } + targetEntry.inv_pointers[ptrName] = { + name: targetMetaName, + guid: sourceGuid + }; + } + }); + }); + + // get sets & inv_set + Promise + .try(() => { + return core.getValidSetNames(node); + }) + .map((setName: string) => { + let targetMemberPathsRaw = core.getMemberPaths(node, setName); + for (let targetMemberPath of targetMemberPathsRaw) { + if (typeof targetMemberPath !== "string") { return; } + let targetPath: string = targetMemberPath; + + Promise + .try(() => { + return core.loadByPath(sponsor.rootNode, targetPath); + }) + .then((targetNode: Node) => { + let targetGuid = core.getGuid(targetNode); + let sets: DictionaryAny = sourceEntry.sets; + let targetMetaNode = core.getBaseType(targetNode); + let targetMetaName = core.getAttribute(targetMetaNode, "name"); + if (typeof targetMetaName === "string") { + let load = { + name: targetMetaName, + guid: targetGuid + }; + let sourceSet = sets[setName]; + if (sourceSet === undefined) { + sets[setName] = [load]; + } else { + sourceSet.push(load); + } + } + let targetEntry = nodeGuidMap[targetGuid]; + if (targetEntry === undefined) { + targetEntry = { + "name": {}, + "guid": targetGuid, + "pointers": {}, "inv_pointers": {}, + "sets": {}, "inv_sets": {} + }; + nodeGuidMap[targetGuid] = targetEntry; + } + let invSets = targetEntry.inv_sets; + let targetSet = invSets[setName]; + let invLoad = { + name: targetMetaName, + guid: sourceGuid + }; + if (targetSet === undefined) { + invSets[setName] = [invLoad]; + } else { + targetSet.push(invLoad); + }; + }) + .catch((err: Error) => { + console.log(`difficulty loading target path: ${targetPath} with err: ${err.message}`); + let load = { + "fault": `could not load member path: ${targetPath}` + }; + let sets: DictionaryAny = sourceEntry.sets; + let sourceSet = sets[setName]; + if (sourceSet === undefined) { + sets[setName] = [load]; + } else { + sourceSet.push(load); + } + }); + } + }); + } finally { + done(); + } + }; + return Promise + .try(() => { + return core.traverse(sponsor.rootNode, + { excludeRoot: false }, + visitFn); + }) + .then(() => { + return nodeGuidMap; + }); + } +} + From 12b8c644f14b7ad802e0a5ec779d5e64965605e4 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Sun, 6 Nov 2016 16:52:38 +0100 Subject: [PATCH 068/131] Add Leadfoot typings (#11733) * Remove global pollution to allow Node.JS and Leadfoot to be included together (Leadfoot uses a part of Dojo but not the conflicting globals). Add Thenable to support Leadfoot typings. * Add leadfoot typings and initial tests. * Remove ... references from tsconfig --- dojo/index.d.ts | 15 +- leadfoot/index.d.ts | 3275 ++++++++++++++++++++++++++++++++++++ leadfoot/leadfoot-tests.ts | 14 + leadfoot/tsconfig.json | 19 + 4 files changed, 3318 insertions(+), 5 deletions(-) create mode 100644 leadfoot/index.d.ts create mode 100644 leadfoot/leadfoot-tests.ts create mode 100644 leadfoot/tsconfig.json diff --git a/dojo/index.d.ts b/dojo/index.d.ts index 11f8a27fbb..b3af7dd779 100644 --- a/dojo/index.d.ts +++ b/dojo/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Michael Van Sickle // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function define(dependencies: String[], factory: Function): any; -declare function require(config?:Object, dependencies?: String[], callback?: Function): any; - declare namespace dojox.dtl { interface __StringArgs { } interface __ObjectArgs { } @@ -16124,8 +16121,12 @@ declare namespace dojo { */ interface instrumentation{(Deferred: any): void} + interface Thenable { + then(onFulfilled?: (value?: T) => Thenable | U, onRejected?: (error?: Error) => Thenable | U): Thenable; + } + interface Callback { - (arg: T): U|Promise; + (arg: T): U|Thenable; } /** @@ -16136,7 +16137,7 @@ declare namespace dojo { * instances of this class. * */ - interface Promise { + interface Promise extends Thenable { /** * Add a callback to be invoked when the promise is resolved * or rejected. @@ -28291,6 +28292,10 @@ declare module "dojo/promise/Promise" { interface Promise extends dojo.promise.Promise { } export = Promise; } +declare module "dojo/promise/Thenable" { + interface Thenable extends dojo.promise.Thenable { } + export = Thenable; +} declare module "dojo/rpc/JsonpService" { var exp: typeof dojo.rpc.JsonpService export=exp; diff --git a/leadfoot/index.d.ts b/leadfoot/index.d.ts new file mode 100644 index 0000000000..eb93321c28 --- /dev/null +++ b/leadfoot/index.d.ts @@ -0,0 +1,3275 @@ +// Type definitions for leadfoot +// Project: https://github.com/theintern/leadfoot +// Definitions by: theintern +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module leadfoot { + + /** + * An error from the remote WebDriver server. + */ + interface WebDriverError extends Error { + /** + * The human-readable error type returned by the WebDriver server. See {@link module:leadfoot/lib/statusCodes} for a + * list of error types. + */ + name: string; + + /** + * A human-readable message describing the error. + */ + message: string; + + /** + * The raw error status code returned by the WebDriver server. + */ + status: number; + + /** + * The raw detail of the error returned by the WebDriver server. + */ + detail: any; + + /** + * The parameters for the request. + */ + request: { + url: string; + method: string; + requestData: {}; + }; + + /** + * The response object for the request. + */ +// response: request.IResponse; + response: any; + + /** + * The stack trace for the request. + */ + stack: string; + } + + /** + * An object that describes an HTTP cookie. + */ + interface WebDriverCookie { + /** + * The name of the cookie. + */ + name: string; + + /** + * The value of the cookie. + */ + value: string; + + /** + * The registered path for the cookie. + */ + path: string; + + /** + * The registered domain for the cookie. + */ + domain: string; + + /** + * True if the cookie should only be transmitted over HTTPS. + */ + secure: boolean; + + /** + * True if the cookie should be inaccessible to client-side scripting. + */ + httpOnly: boolean; + + /** + * The expiration date of the cookie. + */ + expiry: Date; + } + + /** + * An object that describes a geographical location. + */ + interface Geolocation { + /** + * Latitude in WGS84 decimal coordinate system. + */ + latitude: number; + + /** + * Longitude in WGS84 decimal coordinate system. + */ + longitude: number; + + /** + * Altitude in meters above the WGS84 ellipsoid. + */ + altitude: number; + } + + /** + * A remote log entry. + */ + interface LogEntry { + /** + * The timestamp of the entry in seconds since unix epoch. + */ + timestamp: number; + + /** + * The severity level of the entry. This level is not currently normalised. + */ + level: string; + + /** + * The log entry message. + */ + message: string; + } + + /** + * A list of possible capabilities for a remote WebDriver environment. + */ + interface Capabilities { + /** + * Environments with this capability expose the state of the browser’s offline application cache via the WebDriver API. + */ + applicationCacheEnabled?: boolean; + + /** + * Environments with this capability are incapable of clearing or deleting cookies. This issue cannot be worked around. + */ + brokenCookies?: boolean; + + /** + * Environments with this capability do not correctly retrieve the size of a CSS transformed element. This issue is + * automatically corrected. + */ + brokenCssTransformedSize?: boolean; + + /** + * Environments with this capability do not correctly delete cookies. This issue is automatically corrected for cookies + * that are accessible via JavaScript. + */ + brokenDeleteCookie?: boolean; + + /** + * Environments with this capability do not follow the correct event order when double-clicking. This issue is + * automatically corrected. + */ + brokenDoubleClick?: boolean; + + /** + * Environments with this capability return invalid element handles from execute functions. This issue cannot be worked + * around. + */ + brokenExecuteElementReturn?: boolean; + + /** + * Environments with this capability claim fully transparent elements are non-hidden. This issue is automatically + * corrected. + */ + brokenElementDisplayedOpacity?: boolean; + + /** + * Environments with this capability claim elements positioned offscreen to the top/left of the page are non-hidden. + * This issue is automatically corrected. + */ + brokenElementDisplayedOffscreen?: boolean; + + /** + * Environments with this capability do not correctly retrieve the position of a CSS transformed element. This issue is + * automatically corrected. + */ + brokenElementPosition?: boolean; + + /** + * Environments with this capability do not operate correctly when the `flickFinger` method is called. This issue cannot + * be corrected. + */ + brokenFlickFinger?: boolean; + + /** + * Environments with this capability return HTML tag names with the incorrect case. This issue is automatically + * corrected. + */ + brokenHtmlTagName?: boolean; + + /** + * Environments with this capability fail to perform long tap gestures. This issue is not currently corrected. + */ + brokenLongTap?: boolean; + + /** + * Environments with this capability have broken mouse event APIs. This issue is automatically corrected as much as + * possible through JavaScript-based event emulation. + */ + brokenMouseEvents?: boolean; + + /** + * Environments with this capability do not support dragging fingers across the page. This issue is not currently + * corrected. + */ + brokenMoveFinger?: boolean; + + /** + * Environments with this capability do not support browser navigation functions (back, forward, refresh). This issue + * cannot be corrected. + */ + brokenNavigation?: boolean; + + /** + * Environments with this capability incorrectly return an empty string instead of `null` for attributes that do not + * exist when using the `getSpecAttribute` retrieval method. This issue is automatically corrected. + */ + brokenNullGetSpecAttribute?: boolean; + + /** + * Environments with this capability fail to complete calls to refresh a page through the standard WebDriver API. This + * issue is automatically corrected. + */ + brokenRefresh?: boolean; + + /** + * Environments with this capability have broken keyboard event APIs. This issue is automatically corrected as much as + * possible through JavaScript-based event emulation. + */ + brokenSendKeys?: boolean; + + /** + * Environments with this capability incorrectly omit the key/value of the button being submitted. This issue is + * automatically corrected. + */ + brokenSubmitElement?: boolean; + + /** + * Environments with this capability do not operate correctly when the `touchScroll` method is called. This issue is + * automatically corrected. + */ + brokenTouchScroll?: boolean; + + /** + * Environments with this capability cannot switch between windows. This issue cannot be corrected. + */ + brokenWindowSwitch?: boolean; + + /** + * Environments with this capability break when `setWindowPosition` is called. This issue cannot be corrected. + */ + brokenWindowPosition?: boolean; + + /** + * The name of the current environment. + */ + browserName: string; + + /** + * Environments with this capability can use CSS selectors to find elements. + */ + cssSelectorsEnabled?: boolean; + + /** + * Environments with this capability have viewports that can be resized. + */ + dynamicViewport?: boolean; + + /** + * Environments with this capability break when the `getLogTypes` method is called. The list of log types provided here + * are used in lieu of the values provided by the server when calling `getLogTypes`. + */ + fixedLogTypes?: boolean | string[]; + + /** + * Environments with this capability have JavaScript enabled. Leadfoot does not operate in environments without + * JavaScript. + */ + javascriptEnabled?: boolean; + + /** + * Environments with this capability allow the geographic location of the browser to be set and retrieved using the + * WebDriver API. + */ + locationContextEnabled?: boolean; + + /** + * Environments with this capability support interaction via mouse commands. + */ + mouseEnabled?: boolean; + + /** + * Environments with this capability use platform native events instead of emulated events. + */ + nativeEvents?: boolean; + + /** + * The name of the platform on which the current environment is running. + */ + platform: string; + + /** + * Environments with this capability allow files to be uploaded from a remote client. + */ + remoteFiles?: boolean; + + /** + * Environments with this capability allow the rotation of the device to be set and retrieved using the WebDriver API. + */ + rotatable?: boolean; + + /** + * The special key that is used by default on the given platform to perform keyboard shortcuts. + */ + shortcutKey?: string; + + /** + * Environments with this capability support CSS transforms. + */ + supportsCssTransforms?: boolean; + + /** + * Environments with this capability support asynchronous JavaScript execution. + */ + supportsExecuteAsync?: boolean; + + /** + * Environments with this capability support navigation to `data:` URIs. + */ + supportsNavigationDataUris?: boolean; + + /** {boolean} takesScreenshot + * Environments with this capability allow screenshots of the current screen to be taken. + */ + takesScreenshot?: boolean; + + /** + * Environments with this capability support interaction via touch commands. + */ + touchEnabled?: boolean; + + /** + * The version number of the current environment. + */ + version: string; + + /** + * Environments with this capability allow local storage and session storage to be set and retrieved using the + * WebDriver API. + */ + webStorageEnabled?: boolean; + } +} + +declare module 'leadfoot/helpers/pollUntil' { + import Promise = require('dojo/promise/Promise'); + + namespace pollUntil { } + + /** + * A {@link module:leadfoot/Command} helper that polls for a value within the client environment until the value exists + * or a timeout is reached. + * + * @param poller + * The poller function to execute on an interval. The function should return `null` or `undefined` if there is not a + * result. If the poller function throws, polling will halt. + * + * @param args + * An array of arguments to pass to the poller function when it is invoked. Only values that can be serialised to JSON, + * plus {@link module:leadfoot/Element} objects, can be specified as arguments. + * + * @param timeout + * The maximum amount of time to wait for a successful result, in milliseconds. If not specified, the current + * `executeAsync` maximum timeout for the session will be used. + * + * @param pollInterval + * The amount of time to wait between calls to the poller function, in milliseconds. If not specified, defaults to 67ms. + * + * @returns + * A {@link module:leadfoot/Command#then} callback function that, when called, returns a promise that resolves to the + * value returned by the poller function on success and rejects on failure. + * + * @example + * var Command = require('leadfoot/Command'); + * var pollUntil = require('leadfoot/helpers/pollUntil'); + * + * new Command(session) + * .get('http://example.com') + * .then(pollUntil('return document.getElementById("a");', 1000)) + * .then(function (elementA) { + * // element was found + * }, function (error) { + * // element was not found + * }); + * + * @example + * var Command = require('leadfoot/Command'); + * var pollUntil = require('leadfoot/helpers/pollUntil'); + * + * new Command(session) + * .get('http://example.com') + * .then(pollUntil(function (value) { + * var element = document.getElementById('a'); + * return element && element.value === value ? true : null; + * }, [ 'foo' ], 1000)) + * .then(function () { + * // value was set to 'foo' + * }, function (error) { + * // value was never set + * }); + */ + function pollUntil(poller: Function | string, args?: any[], timeout?: number, pollInterval?: number): (value: any) => Promise; + function pollUntil(poller: Function | string, timeout?: number, pollInterval?: number): (value: any) => Promise; + + export = pollUntil; +} + +declare module 'leadfoot/Command' { + import Element = require('leadfoot/Element'); + import Promise = require('dojo/promise/Promise'); + import Thenable = require('dojo/promise/Thenable'); + import Session = require('leadfoot/Session'); + + /** + * The Command class is a chainable, subclassable object type that can be used to execute commands serially against a + * remote WebDriver environment. The standard Command class includes methods from the {@link module:leadfoot/Session} + * and {@link module:leadfoot/Element} classes, so you can perform all standard session and element operations that + * come with Leadfoot without being forced to author long promise chains. + * + * In order to use the Command class, you first need to pass it a {@link module:leadfoot/Session} instance for it to + * use: + * + * ```js + * var command = new Command(session); + * ``` + * + * Once you have created the Command, you can then start chaining methods, and they will execute in order one after + * another: + * + * ```js + * command.get('http://example.com') + * .findByTagName('h1') + * .getVisibleText() + * .then(function (text) { + * assert.strictEqual(text, 'Example Domain'); + * }); + * ``` + * + * Because these operations are asynchronous, you need to use a `then` callback in order to retrieve the value from the + * last method. Command objects are Thenables, which means that they can be used with any Promises/A+ or ES6-confirmant + * Promises implementation, though there are some specific differences in the arguments and context that are provided + * to callbacks; see {@link module:leadfoot/Command#then} for more details. + * + * --- + * + * Each call on a Command generates a new Command object, which means that certain operations can be parallelised: + * + * ```js + * command = command.get('http://example.com'); + * Promise.all([ + * command.getPageTitle(), + * command.findByTagName('h1').getVisibleText() + * ]).then(function (results) { + * assert.strictEqual(results[0], results[1]); + * }); + * ``` + * + * In this example, the commands on line 3 and 4 both depend upon the `get` call completing successfully but are + * otherwise independent of each other and so execute here in parallel. This is different from commands in Intern 1 + * which were always chained onto the last called method within a given test. + * + * --- + * + * Command objects actually encapsulate two different types of interaction: *session* interactions, which operate + * against the entire browser session, and *element* interactions, which operate against specific elements taken from + * the currently loaded page. Things like navigating the browser, moving the mouse cursor, and executing scripts are + * session interactions; things like getting text displayed on the page, typing into form fields, and getting element + * attributes are element interactions. + * + * Session interactions can be performed at any time, from any Command. On the other hand, to perform element + * interactions, you first need to retrieve one or more elements to interact with. This can be done using any of the + * `find` or `findAll` methods, by the `getActiveElement` method, or by returning elements from `execute` or + * `executeAsync` calls. The retrieved elements are stored internally as the *element context* of all chained + * Commands. When an element method is called on a chained Command with a single element context, the result will be + * returned as-is: + * + * ```js + * command = command.get('http://example.com') + * // finds one element -> single element context + * .findByTagName('h1') + * .getVisibleText() + * .then(function (text) { + * // `text` is the text from the element context + * assert.strictEqual(text, 'Example Domain'); + * }); + * ``` + * + * When an element method is called on a chained Command with a multiple element context, the result will be returned + * as an array: + * + * ```js + * command = command.get('http://example.com') + * // finds multiple elements -> multiple element context + * .findAllByTagName('p') + * .getVisibleText() + * .then(function (texts) { + * // `texts` is an array of text from each of the `p` elements + * assert.deepEqual(texts, [ + * 'This domain is established to be used for […]', + * 'More information...' + * ]); + * }); + * ``` + * + * The `find` and `findAll` methods are special and change their behaviour based on the current element filtering state + * of a given command. If a command has been filtered by element, the `find` and `findAll` commands will only find + * elements *within* the currently filtered set of elements. Otherwise, they will find elements throughout the page. + * + * Some method names, like `click`, are identical for both Session and Element APIs; in this case, the element APIs + * are suffixed with the word `Element` in order to identify them uniquely. + * + * --- + * + * Commands can be subclassed in order to add additional functionality without making direct modifications to the + * default Command prototype that might break other parts of the system: + * + * ```js + * function CustomCommand() { + * Command.apply(this, arguments); + * } + * CustomCommand.prototype = Object.create(Command.prototype); + * CustomCommand.prototype.constructor = CustomCommand; + * CustomCommand.prototype.login = function (username, password) { + * return new this.constructor(this, function () { + * return this.parent + * .findById('username') + * .click() + * .type(username) + * .end() + * .findById('password') + * .click() + * .type(password) + * .end() + * .findById('login') + * .click() + * .end(); + * }); + * }; + * ``` + * + * Note that returning `this`, or a command chain starting from `this`, from a callback or command initialiser will + * deadlock the Command, as it waits for itself to settle before settling. + */ + class Command implements Thenable { + /** + * @constructor module:leadfoot/Command + * @param {module:leadfoot/Command|module:leadfoot/Session} parent + * The parent command that this command is chained to, or a {@link module:leadfoot/Session} object if this is the + * first command in a command chain. + * + * @param {function(setContext:Function, value:any): (any|Promise)} initialiser + * A function that will be executed when all parent commands have completed execution. This function can create a + * new context for this command by calling the passed `setContext` function any time prior to resolving the Promise + * that it returns. If no context is explicitly provided, the context from the parent command will be used. + * + * @param {(function(setContext:Function, error:Error): (any|Promise))=} errback + * A function that will be executed if any parent commands failed to complete successfully. This function can create + * a new context for the current command by calling the passed `setContext` function any time prior to resolving the + * Promise that it returns. If no context is explicitly provided, the context from the parent command will be used. + */ + constructor( + parent: Command | Session, + initialiser?: (setContext: Command.ContextSetter, value: any) => Thenable | T, + errback?: (setContext: Command.ContextSetter, error: Error) => Thenable | T + ); + + /** + * The parent Command of the Command, if one exists. + * + * @readonly + */ + parent: Command; + + /** + * The parent Session of the Command. + * + * @readonly + */ + session: Session; + + /** + * The filtered elements that will be used if an element-specific method is invoked. Note that this property is not + * valid until the parent Command has been settled. The context array also has two additional properties: + * + * - isSingle (boolean): If true, the context will always contain a single element. This is used to differentiate + * between methods that should still return scalar values (`find`) and methods that should return arrays of + * values even if there is only one element in the context (`findAll`). + * - depth (number): The depth of the context within the command chain. This is used to prevent traversal into + * higher filtering levels by {@link module:leadfoot/Command#end}. + * + * @readonly + */ + context: Command.Context; + + /** + * The underlying Promise for the Command. + * + * @readonly + */ + promise: Promise; + + /** + * Pauses execution of the next command in the chain for `ms` milliseconds. + * + * @param {number} ms Time to delay, in milliseconds. + * @returns {module:leadfoot/Command.} + */ + sleep(ms: number): Command; + + /** + * Ends the most recent filtering operation in the current Command chain and returns the set of matched elements + * to the previous state. This is equivalent to the `jQuery#end` method. + * + * @example + * command + * .findById('parent') // sets filter to #parent + * .findByClassName('child') // sets filter to all .child inside #parent + * .getVisibleText() + * .then(function (visibleTexts) { + * // all the visible texts from the children + * }) + * .end() // resets filter to #parent + * .end(); // resets filter to nothing (the whole document) + * + * @param numCommandsToPop The number of element contexts to pop. Defaults to 1. + */ + end(numCommandsToPop?: number): Command; + + /** + * Adds a callback to be invoked once the previously chained operation has completed. + * + * This method is compatible with the `Promise#then` API, with two important differences: + * + * 1. The context (`this`) of the callback is set to the Command object, rather than being `undefined`. This allows + * promise helpers to be created that can retrieve the appropriate session and element contexts for execution. + * 2. A second non-standard `setContext` argument is passed to the callback. This `setContext` function can be + * called at any time before the callback fulfills its return value and expects either a single + * {@link module:leadfoot/Element} or an array of Elements to be provided as its only argument. The provided + * element(s) will be used as the context for subsequent element method invocations (`click`, etc.). If + * the `setContext` method is not called, the element context from the parent will be passed through unmodified. + * + * @param {Function=} callback + * @param {Function=} errback + * @returns {module:leadfoot/Command.} + */ + then( + callback: (value: T, setContext?: Command.ContextSetter) => Thenable | U, + errback?: (error: Error, setContext?: Command.ContextSetter) => Thenable | U + ): Command; + + /** + * Adds a callback to be invoked when any of the previously chained operations have failed. + */ + catch(errback: (error: Error, setContext?: Command.ContextSetter) => Thenable | U): Command; + + /** + * Adds a callback to be invoked once the previously chained operations have resolved. + */ + finally(callback: (valueOrError: T | Error, setContext?: Command.ContextSetter) => Thenable | U): Command; + + /** + * Cancels all outstanding chained operations of the Command. Calling this method will cause this command and all + * subsequent chained commands to fail with a CancelError. + */ + cancel(): Command; + + /** + * Gets the current value of a timeout for the session. + * + * @param type The type of timeout to retrieve. One of 'script', 'implicit', or 'page load'. + * @returns The timeout, in milliseconds. + */ + getTimeout(type: string): Command; + + /** + * Sets the value of a timeout for the session. + * + * @param type + * The type of timeout to set. One of 'script', 'implicit', or 'page load'. + * + * @param ms + * The length of time to use for the timeout, in milliseconds. A value of 0 will cause operations to time out + * immediately. + */ + setTimeout(type: string, ms: number): Command; + + /** + * Gets the identifier for the window that is currently focused. + * + * @returns A window handle identifier that can be used with other window handling functions. + */ + getCurrentWindowHandle(): Command; + + /** + * Gets a list of identifiers for all currently open windows. + */ + getAllWindowHandles(): Command; + + /** + * Gets the URL that is loaded in the focused window/frame. + */ + getCurrentUrl(): Command; + + /** + * Navigates the focused window/frame to a new URL. + */ + get(url: string): Command; + + /** + * Navigates the focused window/frame forward one page using the browser’s navigation history. + */ + goForward(): Command; + + /** + * Navigates the focused window/frame back one page using the browser’s navigation history. + */ + goBack(): Command; + + /** + * Reloads the current browser window/frame. + */ + refresh(): Command; + + /** + * Executes JavaScript code within the focused window/frame. The code should return a value synchronously. + * + * @see {@link module:leadfoot/Session#executeAsync} to execute code that returns values asynchronously. + * + * @param script + * The code to execute. If a string value is passed, it will be converted to a function on the remote end. + * + * @param args + * An array of arguments that will be passed to the executed code. Only values that can be serialised to JSON, plus + * {@link module:leadfoot/Element} objects, can be specified as arguments. + * + * @returns + * The value returned by the remote code. Only values that can be serialised to JSON, plus DOM elements, can be + * returned. + */ + execute(script: Function | string, args: any[]): Command; + + /** + * Executes JavaScript code within the focused window/frame. The code must invoke the provided callback in + * order to signal that it has completed execution. + * + * @see {@link module:leadfoot/Session#execute} to execute code that returns values synchronously. + * @see {@link module:leadfoot/Session#setExecuteAsyncTimeout} to set the time until an asynchronous script is + * considered timed out. + * + * @param script + * The code to execute. If a string value is passed, it will be converted to a function on the remote end. + * + * @param args + * An array of arguments that will be passed to the executed code. Only values that can be serialised to JSON, plus + * {@link module:leadfoot/Element} objects, can be specified as arguments. In addition to these arguments, a + * callback function will always be passed as the final argument to the script. This callback function must be + * invoked in order to signal that execution has completed. The return value of the script, if any, should be passed + * to this callback function. + * + * @returns + * The value returned by the remote code. Only values that can be serialised to JSON, plus DOM elements, can be + * returned. + */ + executeAsync(script: Function | string, args: any[]): Command; + + /** + * Gets a screenshot of the focused window and returns it in PNG format. + * + * @returns A buffer containing a PNG image. + */ + takeScreenshot(): Command; + + /** + * Gets a list of input method editor engines available to the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + getAvailableImeEngines(): Command; + + /** + * Gets the currently active input method editor for the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + getActiveImeEngine(): Command; + + /** + * Returns whether or not an input method editor is currently active in the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + isImeActivated(): Command; + + /** + * Deactivates any active input method editor in the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + deactivateIme(): Command; + + /** + * Activates an input method editor in the remote environment. + * As of April 2014, no known remote environments support IME functions. + * + * @param engine The type of IME to activate. + */ + activateIme(engine: string): Command; + + /** + * Switches the currently focused frame to a new frame. + * + * @param id + * The frame to switch to. In most environments, a number or string value corresponds to a key in the + * `window.frames` object of the currently active frame. If `null`, the topmost (default) frame will be used. + * If an Element is provided, it must correspond to a `` or `