diff --git a/README.md b/README.md index 3028c233d0..9f3c4fe78f 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,13 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in * Make changes. Remember to edit tests. * You may also want to add yourself to "Definitions by" section of the package header. - Do this by adding your name to the end of the line, as in `// Definitions by: Alice , Bob `. + - Or if there are more people, it can be multiline + ```typescript + // Definitions by: Alice + // Bob + // Steve + // John + ``` * `npm install -g typescript@2.0` and run `tsc`. When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors. diff --git a/notNeededPackages.json b/notNeededPackages.json index 2bc2de286f..ca42f4d9f5 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -354,6 +354,12 @@ "sourceRepoURL": "https://github.com/blakeembrey/path-case", "asOfVersion": "1.1.2" }, + { + "libraryName": "path-to-regexp", + "typingsPackageName": "path-to-regexp", + "sourceRepoURL": "https://github.com/pillarjs/path-to-regexp", + "asOfVersion": "1.7.0" + }, { "libraryName": "pg-promise", "typingsPackageName": "pg-promise", diff --git a/types/angular-loading-bar/index.d.ts b/types/angular-loading-bar/index.d.ts index 191fc043ed..464974631d 100644 --- a/types/angular-loading-bar/index.d.ts +++ b/types/angular-loading-bar/index.d.ts @@ -30,6 +30,10 @@ declare module 'angular' { * Latency Threshold */ latencyThreshold?: number; + /** + * HTML element selector of parent + */ + parentSelector?: string; } } diff --git a/types/angular-local-storage/index.d.ts b/types/angular-local-storage/index.d.ts index a3bd35d048..f403126d7a 100644 --- a/types/angular-local-storage/index.d.ts +++ b/types/angular-local-storage/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-local-storage v0.1.5 +// Type definitions for angular-local-storage v0.1.6 // Project: https://github.com/grevory/angular-local-storage // Definitions by: Ken Fukuyama // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -60,19 +60,19 @@ declare module 'angular' { */ set(key: string, val: string): boolean; /** - * Directly adds a value to cookies with an expiration. - * Note: Typically used as a fallback if local storage is not supported. - * Returns: Boolean - * @param key - * @param val - * @param daysToExpiry - */ + * Directly adds a value to cookies with an expiration. + * Note: Typically used as a fallback if local storage is not supported. + * Returns: Boolean + * @param key + * @param val + * @param daysToExpiry + */ set(key: string, val: string, daysToExpiry: number): boolean; /** - * Directly get a value from a cookie. - * Returns: value from local storage - * @param key - */ + * Directly get a value from a cookie. + * Returns: value from local storage + * @param key + */ get(key: string): string; /** * Remove directly value from a cookie. @@ -84,8 +84,9 @@ declare module 'angular' { * Remove all data for this app from cookie. */ clearAll(): any; - } + + type StorageType = 'localStorage' | 'sessionStorage'; interface ILocalStorageService { /** @@ -104,19 +105,19 @@ declare module 'angular' { * @param key * @param value */ - set(key: string, value: T): boolean; + set(key: string, value: T, storageType?: StorageType): boolean; /** * Directly get a value from local storage. * If local storage is not supported, use cookies instead. * Returns: value from local storage * @param key */ - get(key: string): T; + get(key: string, storageType?: StorageType): T; /** * Return array of keys for local storage, ignore keys that not owned. * Returns: value from local storage */ - keys(): string[]; + keys(storageType?: StorageType): string[]; /** * Remove an item from local storage by key. * If local storage is not supported, use cookies instead. @@ -131,7 +132,7 @@ declare module 'angular' { * Returns: Boolean * @param regularExpression */ - clearAll(regularExpression?: RegExp): boolean; + clearAll(regularExpression?: RegExp, storageType?: StorageType): boolean; /** * Bind $scope key to localStorageService. * Usage: localStorageService.bind(scope, property, value[optional], key[optional]) @@ -141,7 +142,7 @@ declare module 'angular' { * @param value optional * @param key The corresponding key used in local storage */ - bind(scope: angular.IScope, property: string, value?: any, key?: string): Function; + bind(scope: angular.IScope, property: string, value?: any, key?: string, storageType?: StorageType): Function; /** * Return the derive key * Returns String @@ -152,7 +153,7 @@ declare module 'angular' { * Return localStorageService.length, ignore keys that not owned. * Returns Number */ - length(): number; + length(storageType?: StorageType): number; /** * Deal with browser's cookies directly. */ diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 5afc9a9153..93b92290e4 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -27,7 +27,7 @@ declare module 'angular' { escapeToClose?: boolean; resolve?: ResolveObject; controllerAs?: string; - parent?: ((scope: ng.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node + parent?: ((scope: angular.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node disableParentScroll?: boolean; // default: true } @@ -107,9 +107,9 @@ declare module 'angular' { resolve?: ResolveObject; controllerAs?: string; parent?: string | Element | JQuery; // default: root node - onShowing?(scope: ng.IScope, element: JQuery): void; - onComplete?(scope: ng.IScope, element: JQuery): void; - onRemoving?(element: JQuery, removePromise: ng.IPromise): void; + onShowing?(scope: angular.IScope, element: JQuery): void; + onComplete?(scope: angular.IScope, element: JQuery): void; + onRemoving?(element: JQuery, removePromise: angular.IPromise): void; skipHide?: boolean; multiple?: boolean; fullscreen?: boolean; // default: false @@ -214,6 +214,7 @@ declare module 'angular' { contrastDefaultColor?: string; contrastDarkColors?: string | string[]; contrastLightColors?: string | string[]; + contrastStrongLightColors?: string|string[]; } interface IThemeHues { diff --git a/types/angular-toastr/index.d.ts b/types/angular-toastr/index.d.ts index 7a10587e9b..83c42045d1 100644 --- a/types/angular-toastr/index.d.ts +++ b/types/angular-toastr/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular Toastr v1.6.0 // Project: https://github.com/Foxandxss/angular-toastr -// Definitions by: Niko Kovačič +// Definitions by: Niko Kovačič , Troy McKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -15,9 +15,9 @@ declare module 'angular' { closeHtml?: string; extendedTimeOut?: number; messageClass?: string; - onHidden?: Function; - onShown?: Function; - onTap?: Function; + onHidden?: (wasClicked: boolean, toast: angular.toastr.IToast) => void; + onShown?: (toast: angular.toastr.IToast) => void; + onTap?: (toast: angular.toastr.IToast) => void; progressBar?: boolean; tapToDismiss?: boolean; templates?: { diff --git a/types/angular-ui-bootstrap/index.d.ts b/types/angular-ui-bootstrap/index.d.ts index 1e4d15d282..c09d8cfbb6 100644 --- a/types/angular-ui-bootstrap/index.d.ts +++ b/types/angular-ui-bootstrap/index.d.ts @@ -311,7 +311,7 @@ declare module 'angular' { openClass?: string; } - interface IModalProvider { + interface IModalProvider extends IServiceProvider { /** * Default options all modals will use. */ @@ -875,7 +875,7 @@ declare module 'angular' { useContentExp?: boolean; } - interface ITooltipProvider { + interface ITooltipProvider extends IServiceProvider { /** * Provide a set of defaults for certain tooltip and popover attributes. */ diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index e6be93a6af..d01dbd25b8 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -484,7 +484,14 @@ namespace TestInjector { function foobar(v: boolean): number { return 7; } - let result: number = $injector.invoke(foobar); + let result = $injector.invoke(foobar); + if (!(typeof result === 'number')) { + // This fails to compile if 'result' is not exactly a number. + let expectNever: never = result; + } + + let anyFunction: Function = foobar; + let anyResult: string = $injector.invoke(anyFunction); } } diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 194ccf8205..c895c4f7ee 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.6 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Georgii Dolzhykov +// Definitions by: Diego Vilar , Georgii Dolzhykov , Caleb St-Denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -1847,6 +1847,77 @@ declare namespace angular { $postLink?(): void; } + /** + * Interface for the $onInit lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnInit { + /** + * Called on each controller after all the controllers on an element have been constructed and had their bindings + * initialized (and before the pre & post linking functions for the directives on this element). This is a good + * place to put initialization code for your controller. + */ + $onInit(): void; + } + + /** + * Interface for the $doCheck lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IDoCheck { + /** + * Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. + * Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; + * implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish + * to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's + * change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes, + * you must store the previous value(s) for comparison to the current values. + */ + $doCheck(): void; + } + + /** + * Interface for the $onChanges lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnChanges { + /** + * Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form + * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as + * cloning the bound value to prevent accidental mutation of the outer value. + */ + $onChanges(onChangesObj: IOnChangesObject): void; + } + + /** + * Interface for the $onDestroy lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnDestroy { + /** + * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, + * watches and event handlers. + */ + $onDestroy(): void; + } + + /** + * Interface for the $postLink lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IPostLink { + /** + * Called after this controller's element and its children have been linked. Similar to the post-link function this + * hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain + * templateUrl directives will not have been compiled and linked since they are waiting for their template to load + * asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered + * analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather + * different in Angular 1 there is no direct mapping and care should be taken when upgrading. + */ + $postLink(): void; + } + interface IOnChangesObject { [property: string]: IChangesObject; } @@ -1981,6 +2052,7 @@ declare namespace angular { instantiate(typeConstructor: {new(...args: any[]): T}, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: (...args: any[]) => T, context?: any, locals?: any): T; + invoke(func: Function, context?: any, locals?: any): any; strictDi: boolean; } diff --git a/types/angular/tslint.json b/types/angular/tslint.json index 3ace427c86..50c4474b7c 100644 --- a/types/angular/tslint.json +++ b/types/angular/tslint.json @@ -17,4 +17,4 @@ "unified-signatures": false, "void-return": false } -} +} \ No newline at end of file diff --git a/types/archiver/archiver-tests.ts b/types/archiver/archiver-tests.ts index 57a569ab02..d4ea423a4f 100644 --- a/types/archiver/archiver-tests.ts +++ b/types/archiver/archiver-tests.ts @@ -1,26 +1,36 @@ -import Archiver = require('archiver'); -import FS = require('fs'); +import * as Archiver from 'archiver'; +import * as fs from 'fs'; const archiver = Archiver.create('zip'); -const writeStream = FS.createWriteStream('./archiver.d.ts'); -const readStream = FS.createReadStream('./archiver.d.ts'); +const writeStream = fs.createWriteStream('./archiver.d.ts'); +const readStream = fs.createReadStream('./archiver.d.ts'); archiver.abort(); + +archiver.pipe(writeStream); +archiver.append(readStream, { name: 'archiver.d.ts' }); + archiver.append(readStream, {name: 'archiver.d.ts'}) .append(readStream, {name: 'archiver.d.ts'}); archiver.bulk({ mappaing: {} }); archiver.directory('./path', './someOtherPath'); -archiver.directory('./path', { name: "testName"} ); - +archiver.directory('./path', { name: "testName" }); archiver.directory('./', "", {}); -archiver.directory('./', {name: 'test'}, {}); +archiver.directory('./', { name: 'test' }, {}); + +archiver.append(readStream, { + name: "sub/folder.xml" +}); + +archiver.glob("**", { + cwd: 'path/to/files', +}); +archiver.glob('./path', {}, {}); archiver.file('./path', { name: 'test' }); -archiver.glob('./path', {}, {}); -archiver.finalize(); archiver.setFormat('zip'); archiver.setModule(() => {}); @@ -28,4 +38,4 @@ archiver.setModule(() => {}); archiver.pointer(); archiver.use(() => {}); -archiver.pipe(writeStream); +archiver.finalize(); diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 9c2b2ae509..2e4b1063ff 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -1,51 +1,67 @@ // Type definitions for archiver 1.3 // Project: https://github.com/archiverjs/node-archiver -// Definitions by: Esri +// Definitions by: Esri , Dolan Miu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== import Archiver = require('archiver); var archiver = Archiver.create('zip'); - archiver.pipe(FS.createWriteStream('xxx')); - archiver.append(FS.createReadStream('xxx')); + archiver.pipe(fs.createWriteStream('xxx')); + archiver.append(fs.createReadStream('xxx')); archiver.finalize(); =============================================== */ /// -import * as FS from 'fs'; -import * as STREAM from 'stream'; +import * as fs from 'fs'; +import * as stream from 'stream'; +import * as express from 'express'; +import * as glob from 'glob'; -declare function archiver(format: string, options?: {}): archiver.Archiver; +declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver; declare namespace archiver { - function create(format: string, options?: {}): Archiver; + type Format = 'zip' | 'tar'; + + function create(format: string, options?: ArchiverOptions): Archiver; function registerFormat(format: string, module: Function): void; - interface nameInterface { + interface EntryData { name?: string; + prefix?: string; + stats?: string; } - interface Archiver extends STREAM.Transform { + interface Archiver extends stream.Transform { abort(): this; - append(source: STREAM.Readable | Buffer | string, name: nameInterface): this; + append(source: stream.Readable | Buffer | string, name?: EntryData): this; bulk(mappings: any): this; - directory(dirpath: string, destpath: nameInterface | string, data?: any | Function): this; + directory(dirpath: string, options: EntryData | string, data?: EntryData): this; - file(filepath: string, data: any): this; - glob(pattern: string, options: {}, data: any): this; + file(filename: string, data: EntryData): this; + glob(pattern: string, options?: glob.IOptions, data?: EntryData): this; finalize(): this; + pipe(stream: fs.WriteStream | express.Response): void; + setFormat(format: string): this; setModule(module: Function): this; pointer(): number; use(plugin: Function): this; } + + interface ArchiverOptions { + store?: boolean; + gzip?: boolean; + gzipOptions?: { + level: number, + }; + } } export = archiver; diff --git a/types/auto-sni/auto-sni-tests.ts b/types/auto-sni/auto-sni-tests.ts new file mode 100644 index 0000000000..a271a1a1ad --- /dev/null +++ b/types/auto-sni/auto-sni-tests.ts @@ -0,0 +1,6 @@ +import * as autosni from "auto-sni"; +let a = autosni({ + agreeTos: true, + email: '', + domains: [''] +}); diff --git a/types/auto-sni/index.d.ts b/types/auto-sni/index.d.ts new file mode 100644 index 0000000000..bc252831ca --- /dev/null +++ b/types/auto-sni/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for auto-sni 2.1 +// Project: https://www.npmjs.com/package/auto-sni +// Definitions by: Jan Wolf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import {Server} from "https"; + +declare namespace createServer { + interface Options { + email: string; + agreeTos: boolean; + domains: Array; + ports?: { + http?: number, + https?: number + }; + debug?: boolean; + } +} + +declare function createServer(opts: createServer.Options, app?: any): Server; + +export = createServer; diff --git a/types/auto-sni/tsconfig.json b/types/auto-sni/tsconfig.json new file mode 100644 index 0000000000..715f315867 --- /dev/null +++ b/types/auto-sni/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auto-sni-tests.ts" + ] +} diff --git a/types/auto-sni/tslint.json b/types/auto-sni/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/auto-sni/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 8a37bdf21b..6741bcccd1 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -167,8 +167,14 @@ declare namespace autobahn { interface IPublishOptions { acknowledge?: boolean; exclude?: number[]; + exclude_authid?: string[]; + exclude_authrole?: string[]; eligible?: number[]; - disclose_me?: Boolean; + eligible_authid?: string[]; + eligible_authrole?: string[]; + retain?: boolean; + disclose_me?: boolean; + exclude_me?: boolean; } interface ISubscribeOptions { diff --git a/types/azure/index.d.ts b/types/azure/index.d.ts index 59d1b9d114..8e7a321713 100644 --- a/types/azure/index.d.ts +++ b/types/azure/index.d.ts @@ -1627,7 +1627,7 @@ export interface Entity { RowKey: string; Timestamp?: Date; etag?: string; - [property: string]: string | number | boolean | Date; + [property: string]: string | number | boolean | Date | undefined; } //#endregion //#region BlobService Interfaces diff --git a/types/azure/tsconfig.json b/types/azure/tsconfig.json index 5f058966d7..15e71337b2 100644 --- a/types/azure/tsconfig.json +++ b/types/azure/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index cb02d11ee1..5974a64885 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -14,6 +14,9 @@ traverse(ast, { if (t.isIdentifier(node, { name: "n" })) { node.name = "x"; } + if (t.isFunctionExpression(node)) { + node.params = [t.identifier('param')]; + } } }); @@ -24,3 +27,5 @@ if (t.isBinaryExpression(ast)) { } t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); + +var exp: t.Expression = t.nullLiteral(); diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index b3b0f966c6..77ea8b54de 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for babel-types v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-types -// Definitions by: Troy Gerwien +// Definitions by: Troy Gerwien , Sam Baxter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface Comment { @@ -88,7 +88,7 @@ export interface CallExpression extends Node { export interface CatchClause extends Node { type: "CatchClause"; - param: Pattern; + param: Identifier; body: BlockStatement; } @@ -148,7 +148,7 @@ export interface ForStatement extends Node { export interface FunctionDeclaration extends Node { type: "FunctionDeclaration"; id: Identifier; - params: Pattern[]; + params: Array; body: BlockStatement; generator: boolean; async: boolean; @@ -159,7 +159,7 @@ export interface FunctionDeclaration extends Node { export interface FunctionExpression extends Node { type: "FunctionExpression"; id: Identifier; - params: Pattern[]; + params: Array; body: BlockStatement; generator: boolean; async: boolean; @@ -252,7 +252,7 @@ export interface ObjectMethod extends Node { value: Expression; decorators?: Decorator[]; id: Identifier; - params: Pattern[]; + params: Array; body: BlockStatement; generator: boolean; async: boolean; @@ -353,20 +353,20 @@ export interface WithStatement extends Node { export interface AssignmentPattern extends Node { type: "AssignmentPattern"; - left: Pattern; + left: Identifier; right: Expression; } export interface ArrayPattern extends Node { type: "ArrayPattern"; - elements: Array; + elements: Array; typeAnnotation?: TypeAnnotation; } export interface ArrowFunctionExpression extends Node { type: "ArrowFunctionExpression"; id: Identifier; - params: Pattern[]; + params: Array; body: BlockStatement | Expression; generator: boolean; async: boolean; @@ -472,7 +472,7 @@ export interface ClassMethod extends Node { static: boolean; decorators?: Decorator[]; id: Identifier; - params: Pattern[]; + params: Array; body: BlockStatement; generator: boolean; async: boolean; @@ -870,7 +870,7 @@ export interface SpreadProperty extends Node { argument: Expression; } -export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; export type Binary = BinaryExpression | LogicalExpression; export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; @@ -886,11 +886,11 @@ export type For = ForInStatement | ForStatement | ForOfStatement; export type ForXStatement = ForInStatement | ForOfStatement; export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; -export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; +export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; -export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral; -export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; +export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral; +export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty; export type Method = ObjectMethod | ClassMethod; export type ObjectMember = ObjectMethod | ObjectProperty; @@ -925,8 +925,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; -export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; -export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function functionDeclaration(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; export function identifier(name?: string): Identifier; export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; @@ -940,7 +940,7 @@ export function memberExpression(object?: Expression | Super, property?: Express export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; export function program(body?: Array, directives?: Directive[]): Program; export function objectExpression(properties?: Array): ObjectExpression; -export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean): ObjectMethod; export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; export function returnStatement(argument?: Expression): ReturnStatement; @@ -957,8 +957,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; -export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; -export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: Array, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; export function classBody(body?: Array): ClassBody; export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; @@ -972,7 +972,7 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; export function metaProperty(meta?: string, property?: string): MetaProperty; -export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; export function spreadElement(argument?: Expression): SpreadElement; export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index 4400a8f1a0..eb35a5d799 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -5,10 +5,11 @@ /// -import * as t from 'babel-types'; -type Node = t.Node; +import { File, Expression } from 'babel-types'; -export function parse(code: string, opts?: BabylonOptions): Node; +export function parse(code: string, opts?: BabylonOptions): File; + +export function parseExpression(input: string, options?: BabylonOptions): Expression; export interface BabylonOptions { /** diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index 46f504e18e..a7da55495b 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -292,6 +292,14 @@ function RegionTests() { } +function ViewTests() { + const v = new MyView(new MyModel()); + const isDestroyed: boolean = v.isDestroyed(); + const isRendered: boolean = v.isRendered(); + const isAttached: boolean = v.isAttached(); + const vv: Marionette.View = v.delegateEntityEvents(); +} + function CollectionViewTests() { var cv = new MyCollectionView(); cv.collection.add(new MyModel()); diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index d24f9d64f9..93b82355db 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -856,7 +856,10 @@ declare namespace Marionette { /** * Internal properties extended in Marionette.View. */ - isDestroyed: boolean; + isDestroyed(): boolean; + isRendered(): boolean; + isAttached(): boolean; + delegateEntityEvents(): View; supportsRenderLifecycle: boolean; supportsDestroyLifecycle: boolean; diff --git a/types/backlog-js/index.d.ts b/types/backlog-js/index.d.ts index d06f764baa..e0742c39dd 100644 --- a/types/backlog-js/index.d.ts +++ b/types/backlog-js/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/nulab/backlog-js // Definitions by: Yuichi Watanabe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// -/// declare class Request { private configure; diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index e948668dc7..75560d4e42 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -190,6 +190,11 @@ function CommonMethodsInEventStreamsAndProperties() { console.log(sum); // returns [-1, 2, 8] in an order }); } + + { + var src = Bacon.fromArray([1, 2, 3]); + src.doLog('element value'); + } } function EventStream() { diff --git a/types/baconjs/index.d.ts b/types/baconjs/index.d.ts index 8659ea9115..0550d6ec48 100644 --- a/types/baconjs/index.d.ts +++ b/types/baconjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bacon.js 0.7.0 // Project: https://baconjs.github.io/ -// Definitions by: Alexander Matsievsky +// Definitions by: Alexander Matsievsky , Joonas Javanainen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -69,7 +69,7 @@ declare namespace Bacon { /** * @function * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. - * @param {Promise|JQueryXHR} promise + * @param {PromiseLike|JQueryXHR} promise * @param {boolean} [abort] * @returns {EventStream} * @example @@ -78,7 +78,7 @@ declare namespace Bacon { * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); * Bacon.fromPromise(Promise.resolve(1), false); */ - function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; + function fromPromise(promise:PromiseLike|JQueryXHR, abort?:boolean):EventStream; /** * @callback Bacon.fromPromise~eventTransformer @@ -88,7 +88,7 @@ declare namespace Bacon { /** * @function Bacon.fromPromise * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. - * @param {Promise|JQueryXHR} promise + * @param {PromiseLike|JQueryXHR} promise * @param {boolean} abort * @param {Bacon.fromPromise~eventTransformer} eventTransformer * @returns {EventStream} @@ -100,7 +100,7 @@ declare namespace Bacon { * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; * }); */ - function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; + function fromPromise(promise:PromiseLike|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; /** * @function @@ -1026,9 +1026,10 @@ declare namespace Bacon { /** * @method EventStream#doLog * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @param {string} [label] * @returns {EventStream} */ - doLog():EventStream; + doLog(label?:string):EventStream; /** * @method @@ -1613,9 +1614,10 @@ declare namespace Bacon { /** * @method Property#doLog * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @param {string} [label] * @returns {Property} */ - doLog():Property; + doLog(label?:string):Property; /** * @method diff --git a/types/bleno/bleno-tests.ts b/types/bleno/bleno-tests.ts new file mode 100644 index 0000000000..7dcb47ff35 --- /dev/null +++ b/types/bleno/bleno-tests.ts @@ -0,0 +1,56 @@ +import * as Bleno from 'bleno'; + +export class EchoCharacteristic extends Bleno.Characteristic { + _value: any; + _updateValueCallback: any; + + constructor() { + super({ + uuid: 'ec0e', + properties: ['read', 'write', 'notify'], + value: null + }); + this._value = new ArrayBuffer(0); + this._updateValueCallback = null; + } + + onReadRequest(offset: number, callback: any) { + callback(Bleno.Characteristic.RESULT_SUCCESS, this._value); + } + + onWriteRequest(data: any, offset: number, withoutResponse: boolean, callback: any) { + this._value = data; + + if (this._updateValueCallback) { + this._updateValueCallback(this._value); + } + + callback(Bleno.Characteristic.RESULT_SUCCESS); + } + + onSubscribe(maxValueSize: number, updateValueCallback: any) { + this._updateValueCallback = updateValueCallback; + } + + onUnsubscribefunction() { + this._updateValueCallback = null; + } +} + +Bleno.on('stateChange', (state: string) => { + if (state === 'poweredOn') { + Bleno.startAdvertising('echo', ['ec00'], () => {}); + } else { + Bleno.stopAdvertising(() => {}); + } +}); + +let characteristic = new EchoCharacteristic(); +Bleno.on('advertisingStart', (error: string) => { + if (!error) { + Bleno.setServices( + [new Bleno.PrimaryService({uuid: 'ec00', characteristics: [ characteristic ] })], + () => {} + ); + } +}); diff --git a/types/bleno/index.d.ts b/types/bleno/index.d.ts new file mode 100644 index 0000000000..a59e394a84 --- /dev/null +++ b/types/bleno/index.d.ts @@ -0,0 +1,128 @@ +// Type definitions for bleno 0.4 +// Project: https://github.com/sandeepmistry/bleno +// Definitions by: Manuel Francisco Naranjo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class Characteristic { + uuid: any; + properties: any; + secure: any; + value: any; + descriptors: any; + + constructor(options: any); + + onIndicate(): void; + + onNotify(): void; + + onReadRequest(offset: any, callback: any): void; + + onSubscribe(maxValueSize: any, updateValueCallback: any): void; + + onUnsubscribe(): void; + + onWriteRequest(data: any, offset: any, withoutResponse: any, callback: any): void; + + toString(): any; + + static RESULT_ATTR_NOT_LONG: number; + + static RESULT_INVALID_ATTRIBUTE_LENGTH: number; + + static RESULT_INVALID_OFFSET: number; + + static RESULT_SUCCESS: number; + + static RESULT_UNLIKELY_ERROR: number; +} + +export class Descriptor { + uuid: any; + value: any; + + constructor(options: any); + + toString(): any; +} + +export class PrimaryService { + uuid: any; + characteristics: any; + + constructor(options: any); + + toString(): any; +} + +export const address: string; + +export const domain: any; + +export const mtu: number; + +export const platform: string; + +export const rssi: number; + +export const state: string; + +export function addListener(type: any, listener: any): any; + +export function disconnect(): void; + +export function emit(type: any, ...args: any[]): any; + +export function eventNames(): any; + +export function getMaxListeners(): any; + +export function listenerCount(type: any): any; + +export function listeners(type: any): any; + +export function on(type: any, listener: any): any; + +export function onAccept(clientAddress: any): void; + +export function onAddressChange(address: any): void; + +export function onAdvertisingStart(error: any): void; + +export function onAdvertisingStop(): void; + +export function onDisconnect(clientAddress: any): void; + +export function onMtuChange(mtu: any): void; + +export function onPlatform(platform: any): void; + +export function onRssiUpdate(rssi: any): void; + +export function onServicesSet(error: any): void; + +export function onStateChange(state: any): void; + +export function once(type: any, listener: any): any; + +export function prependListener(type: any, listener: any): any; + +export function prependOnceListener(type: any, listener: any): any; + +export function removeAllListeners(type: any, ...args: any[]): any; + +export function removeListener(type: any, listener: any): any; + +export function setMaxListeners(n: any): any; + +export function setServices(services: any, callback: any): void; + +export function startAdvertising(name: any, serviceUuids: any, callback: any): void; + +export function startAdvertisingIBeacon(uuid: any, major: any, minor: any, measuredPower: any, callback: any): void; + +export function startAdvertisingWithEIRData(advertisementData: any, scanData: any, callback: any): void; + +export function stopAdvertising(callback: any): void; + +export function updateRssi(callback: any): void; diff --git a/types/bleno/tsconfig.json b/types/bleno/tsconfig.json new file mode 100644 index 0000000000..44fa6c893f --- /dev/null +++ b/types/bleno/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bleno-tests.ts" + ] +} diff --git a/types/bleno/tslint.json b/types/bleno/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/types/bleno/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 24b6fddaf3..b08f77b3b1 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -44,7 +44,7 @@ declare namespace Blessed { track?: {bg?: string; fg?: string;}; scrollbar?: {bg?: string; fg?: string;}; } - + export type TBorder = { /** * Type of border (line or bg). bg by default. @@ -57,15 +57,15 @@ declare namespace Blessed { /** * Border foreground and background, must be numbers (-1 for default). */ - bg?: number; + bg?: number; fg?: number; /** * Border attributes. */ - bold?: string; + bold?: string; underline?: string; } - + export type TCursor = { /** * Have blessed draw a custom cursor and hide the terminal cursor (experimental). @@ -85,26 +85,26 @@ declare namespace Blessed { color: string; } - export type TAlign = "left" | "center" | "right"; + export type TAlign = "left" | "center" | "right"; - export type ListbarCommand = { - key: string; + export type ListbarCommand = { + key: string; callback: () => void; - }; + }; export type TImage = { /** * Pixel width. */ - width: number; + width: number; /** * Pixel height. */ height: number; /** * Image bitmap. - * */ - bmp: any; + * */ + bmp: any; /** * Image cellmap (bitmap scaled down to cell size). */ @@ -132,13 +132,13 @@ declare namespace Blessed { } export module Events { - + export interface IMouseEventArg { x: number; y: number; action: Types.TMouseAction; } - + export interface IKeyEventArg { full: string; name: string; @@ -148,7 +148,7 @@ declare namespace Blessed { sequence: string; } } - + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; @@ -163,14 +163,14 @@ declare namespace Blessed { export interface IDestroyable { destroy(): void; } - + export interface IOptions { } - + export interface IHasOptions { options: T; } - + export interface TputsOptions extends IOptions { terminal?: string; extended?: boolean; @@ -201,7 +201,7 @@ declare namespace Blessed { termcapFile: string; error: Error; terminal: string; - + setup(): void; term(is: any): boolean; readTerminfo(term: string): string; @@ -233,11 +233,11 @@ declare namespace Blessed { strings: Object; }; } - + export interface IDestroyable { destroy(): void; } - + export interface INodeOptions extends IOptions { name?: string; screen?: Screen; @@ -245,7 +245,7 @@ declare namespace Blessed { children?: Node[]; focusable?: boolean; } - + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { constructor(options: INodeOptions); @@ -257,7 +257,7 @@ declare namespace Blessed { * Original options object. */ options: INodeOptions; - + /** * An object for any miscellanous user data. */ @@ -290,7 +290,7 @@ declare namespace Blessed { * Array of node's children. */ children: Node[]; - + // ** methods ** // /** @@ -398,7 +398,7 @@ declare namespace Blessed { */ on(event: "detach", callback: (arg: Node) => void): this; } - + export class NodeWithEvents extends Node { // ** methods ** // @@ -417,7 +417,7 @@ declare namespace Blessed { removeKey(name: string, listener: Function): void; // ** events ** // - + on(event: string, listener: Function): this; /** * Received on screen resize. @@ -451,12 +451,12 @@ declare namespace Blessed { */ //on(event: "key", callback: (arg: BlessedScreen) => void): this; /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * Received when the terminal window focuses/blurs. Requires a terminal supporting the * focus protocol and focus needs to be passed to program.enableMouse(). */ on(event: "focus", callback: (arg: Screen) => void): this; /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * Received when the terminal window focuses/blurs. Requires a terminal supporting the * focus protocol and focus needs to be passed to program.enableMouse(). */ on(event: "blur", callback: (arg: Screen) => void): this; @@ -492,31 +492,31 @@ declare namespace Blessed { * Received when element becomes hidden. */ on(event: "hide", callback: () => void): this; - + on(event: "set content", callback: () => void): this; on(event: "parsed content", callback: () => void): this; } - + export interface IScreenOptions extends INodeOptions { /** * The blessed Program to be associated with. Will be automatically instantiated if none is provided. */ program?: BlessedProgram; /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, * however, it is more optimal for terminal rendering. */ smartCSR?: boolean; /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, * but may cause flickering depending on what is on each side of the element. */ fastCSR?: boolean; /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at * the cost of overhead within node. */ useBCE?: boolean; @@ -529,13 +529,13 @@ declare namespace Blessed { */ tabSize?: number; /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended * option. It may become default in the future). */ autoPadding?: boolean; - + cursor?: Types.TCursor; - + /** * Create a log file. See log method. */ @@ -545,31 +545,31 @@ declare namespace Blessed { */ dump?: string; /** - * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when * pressing F12. It will display all log and debug messages. */ debug?: (...msg: string[]) => void; /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful * for creating a key that will always exit no matter whether the keys are locked. */ ignoreLocked?: boolean; /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position + * Automatically "dock" borders with other elements instead of overlapping, depending on position * (experimental). For example: These border-overlapped elements: */ dockBorders?: boolean; /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option + * Normally, dockable borders will not dock if the colors or attributes are different. This option * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. */ ignoreDockContrast?: boolean; /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply * removes them from an element's content if iTerm2 is detected). */ fullUnicode?: boolean; @@ -582,17 +582,17 @@ declare namespace Blessed { */ warnings?: boolean; /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. * If value is true unicode is forced. If value is false non-unicode is forced (default: null). */ forceUnicode?: boolean; /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * Input and output streams. process.stdin/process.stdout by default, however, it could be a * net.Socket if you want to make a program that runs over telnet or something of that nature. * */ input?: stream.Writable; /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * Input and output streams. process.stdin/process.stdout by default, however, it could be a * net.Socket if you want to make a program that runs over telnet or something of that nature. * */ output?: stream.Readable; @@ -673,13 +673,13 @@ declare namespace Blessed { */ title?: string; } - + export class Screen extends NodeWithEvents implements IHasOptions { constructor(opts: IScreenOptions); // ** properties ** // cleanSides: any; - + /** * Original options object. */ @@ -690,20 +690,20 @@ declare namespace Blessed { */ program: BlessedProgram; /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, * however, it is more optimal for terminal rendering. */ smartCSR: boolean; /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, * but may cause flickering depending on what is on each side of the element. */ fastCSR: boolean; /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at * the cost of overhead within node. */ useBCE: boolean; @@ -716,38 +716,38 @@ declare namespace Blessed { */ tabSize: number; /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended * option. It may become default in the future). */ autoPadding: boolean; - + cursor: Types.TCursor; - + /** * Dump all output and input to desired file. Can be used together with log option if set as a boolean. */ dump: string; /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful * for creating a key that will always exit no matter whether the keys are locked. */ ignoreLocked: boolean; /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position + * Automatically "dock" borders with other elements instead of overlapping, depending on position * (experimental). For example: These border-overlapped elements: */ dockBorders: boolean; /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option + * Normally, dockable borders will not dock if the colors or attributes are different. This option * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. */ ignoreDockContrast: boolean; /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply * removes them from an element's content if iTerm2 is detected). */ fullUnicode: boolean; @@ -760,17 +760,17 @@ declare namespace Blessed { */ warnings: boolean; /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. * If value is true unicode is forced. If value is false non-unicode is forced (default: null). */ forceUnicode: boolean; /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * Input and output streams. process.stdin/process.stdout by default, however, it could be a * net.Socket if you want to make a program that runs over telnet or something of that nature. * */ input: stream.Writable; /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * Input and output streams. process.stdin/process.stdout by default, however, it could be a * net.Socket if you want to make a program that runs over telnet or something of that nature. * */ output: stream.Readable; @@ -850,9 +850,9 @@ declare namespace Blessed { * Set or get window title. */ title: string; - + // ** methods ** // - + /** * Write string to the log file if one was created. */ @@ -860,7 +860,7 @@ declare namespace Blessed { /** * Same as the log method, but only gets called if the debug option was set. */ - debug(...msg: string[]): void; + debug(...msg: string[]): void; /** * Allocate a new pending screen buffer and a new output screen buffer. */ @@ -959,13 +959,13 @@ declare namespace Blessed { */ deleteTop(top: number, bottom: number): void; /** - * Enable mouse events for the screen and optionally an element (automatically called when a form of + * Enable mouse events for the screen and optionally an element (automatically called when a form of * on('mouse') is bound). */ enableMouse(el: BlessedElement): void; enableMouse(): void; /** - * Enable keypress events for the screen and optionally an element (automatically called when a form of + * Enable keypress events for the screen and optionally an element (automatically called when a form of * on('keypress') is bound). */ enableKeys(el: BlessedElement): void; @@ -980,7 +980,7 @@ declare namespace Blessed { */ copyToClipboard(text: string): void; /** - * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution * to this). Returns true if successful. */ cursorShape(shape: boolean, blink: boolean): any; @@ -993,14 +993,14 @@ declare namespace Blessed { */ cursorReset(): void; /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only + * Take an SGR screenshot of the screen within the region. Returns a string containing only * characters and SGR codes. Can be displayed by simply echoing it in a terminal. */ screenshot(xi: number, xl: number, yi: number, yl: number): string; screenshot(): void; /** - * Destroy the screen object and remove it from the global list. Also remove all global events relevant - * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset * to its initial state. */ destroy(): void; @@ -1043,23 +1043,23 @@ declare namespace Blessed { /** * Border foreground and background, must be numbers (-1 for default). */ - bg?: number; + bg?: number; fg?: number; /** * Border attributes. */ - bold?: string; + bold?: string; underline?: string; } export interface ElementOptions extends INodeOptions { tags?: boolean; - - fg?: string; - bg?: string; - bold?: string; + + fg?: string; + bg?: string; + bold?: string; underline?: string; - + style?: any; /** * Border object, see below. @@ -1107,24 +1107,24 @@ declare namespace Blessed { */ shrink?: boolean; /** - * Amount of padding on the inside of the element. Can be a number or an object containing + * Amount of padding on the inside of the element. Can be a number or an object containing * the properties: left, right, top, and bottom. */ padding?: number | Padding; - + top?: Types.TTopLeft; left?: Types.TTopLeft; right?: Types.TPosition; bottom?: Types.TPosition; - + /** - * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). * Percentages can also have offsets (50%+1, 50%-1). */ width?: number | string; /** - * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or - * keyword (center). right and bottom do not accept keywords. Percentages can also have + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have * offsets (50%+1, 50%-1). */ height?: number | string; @@ -1171,7 +1171,7 @@ declare namespace Blessed { // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { constructor(opts: ElementOptions); - + // ** properties ** // /** @@ -1196,28 +1196,28 @@ declare namespace Blessed { /** * Border foreground and background, must be numbers (-1 for default). */ - bg: number; + bg: number; fg: number; /** * Border attributes. */ - bold: string; + bold: string; underline: string; /** * Calculated width. */ - width: number | string; + width: number | string; /** * Calculated height. */ height: number | string; /** - * Calculated relative top offset.*/ - top: Types.TTopLeft; + * Calculated relative top offset.*/ + top: Types.TTopLeft; /** * Calculated relative left offset. - */ - left: Types.TTopLeft; + */ + left: Types.TTopLeft; /** * Calculated relative right offset. */ @@ -1228,12 +1228,12 @@ declare namespace Blessed { bottom: Types.TPosition; /** * Calculated absolute top offset. - */ - atop: Types.TTopLeft; + */ + atop: Types.TTopLeft; /** * Calculated absolute left offset. - */ - aleft: Types.TTopLeft; + */ + aleft: Types.TTopLeft; /** * Calculated absolute right offset. */ @@ -1241,13 +1241,13 @@ declare namespace Blessed { /** * Calculated absolute bottom offset. */ - abottom: Types.TPosition; + abottom: Types.TPosition; /** * Whether the element is draggable. Set to true to allow dragging. */ - draggable: boolean; - + draggable: boolean; + itop: Types.TTopLeft; ileft: Types.TTopLeft; iheight: Types.TPosition; @@ -1255,115 +1255,115 @@ declare namespace Blessed { /** * Calculated relative top offset. - */ + */ rtop: Types.TTopLeft; /** * Calculated relative left offset. - */ + */ rleft: Types.TTopLeft; /** * Calculated relative right offset. - */ + */ rright: Types.TPosition; /** * Calculated relative bottom offset. - */ + */ rbottom: Types.TPosition; - + lpos: PositionCoords; - + // ** methods ** // - + /** * Write content and children to the screen buffer. */ render(): Coords; /** - * Hide element.*/ - hide(): void; + * Hide element.*/ + hide(): void; /** * Show element. */ - show(): void; + show(): void; /** * Toggle hidden/shown. */ toggle(): void; /** * Focus element. - */ - focus(): void; + */ + focus(): void; /** - * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * Same asel.on('screen', ...) except this will automatically keep track of which listeners * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). */ - onScreenEvent(type: string, handler: Function): void; + onScreenEvent(type: string, handler: Function): void; /** - * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * Same asel.removeListener('screen', ...) except this will automatically keep track of which * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). */ removeScreenEvent(type: string, handler: Function): void; /** - * Free up the element. Automatically unbind all events that may have been bound to the screen - * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), * and destroy(). - */ - free(): void; + */ + free(): void; /** - * Same as the detach() method, except this will automatically call free() and unbind any screen + * Same as the detach() method, except this will automatically call free() and unbind any screen * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). */ - destroy(): void; + destroy(): void; /** * Set the z-index of the element (changes rendering order). */ setIndex(z: number): void; /** - * Put the element in front of its siblings.*/ - setFront(): void; + * Put the element in front of its siblings.*/ + setFront(): void; /** * Put the element in back of its siblings. */ - setBack(): void; + setBack(): void; /** * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} */ setLabel(arg: string | LabelOptions): void; /** * Remove the label completely. - */ - removeLabel(): any; + */ + removeLabel(): any; /** - * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute * in the browser. Example options: {text:'foo'} */ setHover(arg: string | LabelOptions): void; /** * Remove the hover label completely. - */ - removeHover(): void; + */ + removeHover(): void; /** * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). */ enableMouse(): void; /** * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). - */ - enableKeys(): void; + */ + enableKeys(): void; /** * Enable key and mouse events. Calls bot enableMouse and enableKeys. */ enableInput(): void; /** * Enable dragging of the element. - */ - enableDrag(): void; + */ + enableDrag(): void; /** * Disable dragging of the element. */ - disableDrag(): void; + disableDrag(): void; /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only + * Take an SGR screenshot of the screen within the region. Returns a string containing only * characters and SGR codes. Can be displayed by simply echoing it in a terminal. */ screenshot(xi: number, xl: number, yi: number, yl: number): string; @@ -1372,132 +1372,132 @@ declare namespace Blessed { /* Content Methods - Methods for dealing with text content, line by line. Useful for writing a text editor, + Methods for dealing with text content, line by line. Useful for writing a text editor, irc client, etc. - Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() - on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending on how long the original line was. - The lines parameter can be a string or an array of strings. The line parameter must + The lines parameter can be a string or an array of strings. The line parameter must be a string. */ /** - * Set the content. Note: When text is input, it will be stripped of all non-SGR - * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced * with SGR codes (if enabled). */ setContent(text: string): void; /** * Return content, slightly different from el.content. Assume the above formatting. - */ - getContent(): string; + */ + getContent(): string; /** * Similar to setContent, but ignore tags and remove escape codes. */ setText(text: string): void; /** * Similar to getContent, but return content with tags and escape codes removed. - */ - getText(): string; + */ + getText(): string; /** * Insert a line into the box's content. */ insertLine(i: number, lines: string | string[]): void; /** * Delete a line from the box's content. - */ - deleteLine(i: number): void; + */ + deleteLine(i: number): void; /** * Get a line from the box's content. */ - getLine(i: number): string; + getLine(i: number): string; /** * Get a line from the box's content from the visible top. */ - getBaseLine(i: number): string; + getBaseLine(i: number): string; /** * Set a line in the box's content. */ - setLine(i: number, line: string | string[]): void; + setLine(i: number, line: string | string[]): void; /** * Set a line in the box's content from the visible top. */ setBaseLine(i: number, line: string | string[]): void; /** * Clear a line from the box's content. - */ - clearLine(i: number): void; + */ + clearLine(i: number): void; /** * Clear a line from the box's content from the visible top. */ - clearBaseLine(i: number): void; + clearBaseLine(i: number): void; /** * Insert a line at the top of the box. */ - insertTop(lines: string | string[]): void; + insertTop(lines: string | string[]): void; /** * Insert a line at the bottom of the box. */ insertBottom(lines: string | string[]): void; /** * Delete a line at the top of the box. - */ - deleteTop(): void; + */ + deleteTop(): void; /** * Delete a line at the bottom of the box. */ - deleteBottom(): void; + deleteBottom(): void; /** * Unshift a line onto the top of the content. */ unshiftLine(lines: string | string[]): void; /** * Shift a line off the top of the content. - */ - shiftLine(i: number): void; + */ + shiftLine(i: number): void; /** * Push a line onto the bottom of the content. */ pushLine(lines: string | string[]): void; /** * Pop a line off the bottom of the content. - */ + */ popLine(i: number): string; /** * An array containing the content lines. - */ - getLines(): string[]; + */ + getLines(): string[]; /** * An array containing the lines as they are displayed on the screen. */ - getScreenLines(): string[]; + getScreenLines(): string[]; /** - * Get a string's displayed width, taking into account double-width, surrogate pairs, + * Get a string's displayed width, taking into account double-width, surrogate pairs, * combining characters, tags, and SGR escape codes. */ - strWidth(text: string): string; + strWidth(text: string): string; // ** events ** // } - + export interface ScrollableBoxOptions extends ElementOptions { /** * A limit to the childBase. Default is Infinity. */ - baseLimit?: number; + baseLimit?: number; /** - * A option which causes the ignoring of childOffset. This in turn causes the + * A option which causes the ignoring of childOffset. This in turn causes the * childBase to change every time the element is scrolled. */ - alwaysScroll?: boolean; + alwaysScroll?: boolean; /** * Object enabling a scrollbar. * Style of the scrollbar track if present (takes regular style options). */ scrollbar?: { style?: any; track?: any; ch?: string; } - } + } export interface ScrollableTextOptions extends ScrollableBoxOptions { /** @@ -1507,18 +1507,18 @@ declare namespace Blessed { mouse?: boolean | (() => void); /** * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). - */ - keys?: string | string[] | boolean; + */ + keys?: string | string[] | boolean; /** * Use vi keys with the keys option. */ vi?: boolean; } - + export interface BoxOptions extends ScrollableTextOptions { bindings?: any; } - + /** * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. */ @@ -1526,60 +1526,60 @@ declare namespace Blessed { /** * The offset of the top of the scroll content. */ - childBase: number; + childBase: number; /** * The offset of the chosen item/line. */ childOffset: number; - + /** * Scroll the content by a relative offset. */ - scroll(offset: number, always?: boolean): void; + scroll(offset: number, always?: boolean): void; /** * Scroll the content to an absolute index. */ - scrollTo(index: number): void; + scrollTo(index: number): void; /** * Same as scrollTo. */ - setScroll(index: number): void; + setScroll(index: number): void; /** * Set the current scroll index in percentage (0-100). */ setScrollPerc(perc: number): void; /** * Get the current scroll index in lines. - */ - getScroll(): void; + */ + getScroll(): number; /** * Get the actual height of the scrolling area. */ - getScrollHeight(): void; + getScrollHeight(): number; /** * Get the current scroll index in percentage. - */ - getScrollPerc(): void; + */ + getScrollPerc(): number; /** * Reset the scroll index to its initial state. - */ - resetScroll(): void; - + */ + resetScroll(): void; + on(event: string, listener: Function): this; /** * Received when the element is scrolled. */ on(event: "scroll", callback: () => void): this; } - + /** * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. - * A scrollable text box which can display and scroll text, as well as handle + * A scrollable text box which can display and scroll text, as well as handle * pre-existing newlines and escape codes. */ export class ScrollableTextElement extends ScrollableBoxElement { } - + /** * A box element which draws a simple box containing content or other elements. */ @@ -1594,7 +1594,7 @@ declare namespace Blessed { export interface TextOptions extends ElementOptions { /** - * Fill the entire line with chosen bg until parent bg ends, even if there + * Fill the entire line with chosen bg until parent bg ends, even if there * is not enough text to fill the entire width. */ fill?: boolean; @@ -1609,13 +1609,13 @@ declare namespace Blessed { */ export class TextElement extends BlessedElement implements IHasOptions { constructor(opts: TextOptions); - + /** * Original options object. */ options: TextOptions; } - + /** * A simple line which can be line or bg styled. */ @@ -1632,51 +1632,51 @@ declare namespace Blessed { fg?: string; ch?: string; } - + /** * A simple line which can be line or bg styled. */ export class LineElement extends BoxElement implements IHasOptions { constructor(opts: LineOptions); - + /** * Original options object. */ options: LineOptions; } - + export interface BigTextOptions extends BoxOptions { /** * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). */ - font?: string; + font?: string; /** * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). */ fontBold?: string; /** * foreground character. (default: ' ') - */ + */ fch?: string; } - + /** * A box which can render content drawn as 8x14 cell characters using the terminus font. */ export class BigTextElement extends BoxElement implements IHasOptions { constructor(opts: BigTextOptions); - + /** * Original options object. */ options: BigTextOptions; } - + export interface ListElementStyle { selected?: any; item?: any; } - + export interface ListOptions extends BoxOptions { /** * Style for a selected item. Style for an unselected item. @@ -1687,9 +1687,9 @@ declare namespace Blessed { */ items?: string[]; /** - * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a - * callback function which should be called with the search string. The search string is then used to - * jump to an item that is found in items. + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. */ search?: () => void; /** @@ -1701,10 +1701,10 @@ declare namespace Blessed { */ invertSelected?: boolean; } - + export class ListElement extends BoxElement implements IHasOptions> { constructor(opts: ListOptions); - + /** * Original options object. */ @@ -1712,11 +1712,11 @@ declare namespace Blessed { /** * Add an item based on a string. - */ + */ add(text: string): void; /** * Add an item based on a string. - */ + */ addItem(text: string): void; /** * Removes an item from the list. Child can be an element, index, or string. @@ -1724,75 +1724,75 @@ declare namespace Blessed { removeItem(child: BlessedElement): BlessedElement; /** * Push an item onto the list. - * */ + * */ pushItem(child: BlessedElement): number; /** * Pop an item off the list. - * */ - popItem(): BlessedElement; + * */ + popItem(): BlessedElement; /** * Unshift an item onto the list. */ unshiftItem(child: BlessedElement): number; /** * Shift an item off the list. - * */ - shiftItem(): BlessedElement; + * */ + shiftItem(): BlessedElement; /** * Inserts an item to the list. Child can be an element, index, or string. */ - insertItem(i: number, child: BlessedElement): void; + insertItem(i: number, child: BlessedElement): void; /** * Returns the item element. Child can be an element, index, or string. */ - getItem(child: BlessedElement): BlessedElement; + getItem(child: BlessedElement): BlessedElement; /** * Set item to content. */ setItem(child: BlessedElement, content: BlessedElement | string): void; /** * Remove and insert items to the list. - * */ + * */ spliceItem(i: number, n: number, ...items: BlessedElement[]): void; /** * Clears all items from the list. - * */ - clearItems(): void; + * */ + clearItems(): void; /** * Sets the list items to multiple strings. */ - setItems(items: BlessedElement[]): void; + setItems(items: BlessedElement[]): void; /** * Returns the item index from the list. Child can be an element, index, or string. */ getItemIndex(child: BlessedElement): number; /** * Select an index of an item. - * */ + * */ select(index: number): void; /** * Select item based on current offset. - * */ + * */ move(offset: number): void; /** * Select item above selected. - * */ - up(amount: number): void; + * */ + up(amount: number): void; /** * Select item below selected. */ - down(amount: number): void; + down(amount: number): void; /** * Show/focus list and pick an item. The callback is executed with the result. */ - pick(callback: () => void): void; + pick(callback: () => void): void; /** * Find an item based on its text content. */ - fuzzyFind(arg: string | RegExp | (() => void)): void; - + fuzzyFind(arg: string | RegExp | (() => void)): void; + // ** events ** // - + on(event: string, listener: Function): this; /** * Received when an item is selected. @@ -1806,7 +1806,7 @@ declare namespace Blessed { * Either a select or a cancel event was received. */ on(event: "action", callback: () => void): this; - + on(event: "create item", callback: () => void): this; on(event: "add item", callback: () => void): this; on(event: "remove item", callback: () => void): this; @@ -1814,17 +1814,17 @@ declare namespace Blessed { on(event: "set items", callback: () => void): this; on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; } - + export interface FileManagerOptions extends ListOptions { /** * Current working directory. */ cwd?: string; } - + export class FileManagerElement extends ListElement implements IHasOptions { constructor(opts: FileManagerOptions); - + /** * Original options object. */ @@ -1833,7 +1833,7 @@ declare namespace Blessed { * Current working directory. */ cwd: string; - + /** * Refresh the file list (perform a readdir on cwd and update the list items). */ @@ -1851,9 +1851,9 @@ declare namespace Blessed { reset(cwd:string, callback: () => void): void; reset(callback: () => void): void; reset(): void; - + // ** events ** // - + on(event: string, listener: Function): this; /** * Received when an item is selected. @@ -1863,11 +1863,11 @@ declare namespace Blessed { * Received when an item is selected. */ on(event: "file", callback: (file: string) => void): this; - + on(event: "error", callback: (err: any, file: string) => void): this; on(event: "refresh", callback: () => void): this; } - + export interface StyleListTable extends ListElementStyle { /** * Header style. @@ -1878,7 +1878,7 @@ declare namespace Blessed { */ cell?: any; } - + export interface ListTableOptions extends ListOptions { /** * Array of array of strings representing rows. @@ -1886,7 +1886,7 @@ declare namespace Blessed { rows?: string[]; data?: string[][]; /** - * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side * (only useful if the width is shrunken). */ pad?: number; @@ -1894,22 +1894,22 @@ declare namespace Blessed { * Do not draw inner cells. */ noCellBorders?: boolean; - + style?: StyleListTable; } - + export class ListTableElement extends ListElement implements IHasOptions { constructor(opts: ListTableOptions); - + /** * Original options object. */ options: ListTableOptions; - + /** * Set rows in table. Array of arrays of strings. * @example: - * + * * table.setData([ [ 'Animals', 'Foods' ], [ 'Elephant', 'Apple' ], @@ -1920,7 +1920,7 @@ declare namespace Blessed { /** * Set rows in table. Array of arrays of strings. * @example: - * + * * table.setData([ [ 'Animals', 'Foods' ], [ 'Elephant', 'Apple' ], @@ -1929,11 +1929,11 @@ declare namespace Blessed { */ setData(rows: string[][]): void; } - + export interface ListbarOptions extends BoxOptions { style?: ListElementStyle; /** - * Set buttons using an object with keys as titles of buttons, containing of objects + * Set buttons using an object with keys as titles of buttons, containing of objects * containing keys of keys and callback. */ commands: Types.ListbarCommand[]; @@ -1943,15 +1943,15 @@ declare namespace Blessed { */ autoCommandKeys: boolean; } - + export class ListbarElement extends BoxElement implements IHasOptions { constructor(opts: ListbarOptions); - + /** * Original options object. */ options: ListbarOptions; - + /** * Set commands (see commands option above). */ @@ -1990,18 +1990,18 @@ declare namespace Blessed { moveRight(offset: number): void; /** * Select button and execute its callback. - */ + */ selectTab(index: number): void; - + // ** events ** // - + on(event: string, listener: Function): this; on(event: "set items", callback: () => void): this; on(event: "remove item", callback: () => void): this; on(event: "select tab", callback: () => void): this; } - + export interface FormOptions extends BoxOptions { /** * Allow default keys (tab, vi keys, enter). @@ -2015,7 +2015,7 @@ declare namespace Blessed { export class FormElement extends BoxElement implements IHasOptions { constructor(opts: FormOptions); - + /** * Original options object. */ @@ -2024,7 +2024,7 @@ declare namespace Blessed { * Last submitted data. */ submission: TFormData; - + /** * Focus next form element. */ @@ -2045,9 +2045,9 @@ declare namespace Blessed { * Clear the form. */ reset(): void; - + // ** events ** // - + on(event: string, listener: Function): this; /** * Form is submitted. Receives a data object. @@ -2062,7 +2062,7 @@ declare namespace Blessed { */ on(event: "reset", callback: () => void): this; } - + export interface InputOptions extends BoxOptions { } export abstract class InputElement extends BoxElement { @@ -2078,20 +2078,20 @@ declare namespace Blessed { */ inputOnFocus?: boolean; } - + export class TextareaElement extends InputElement implements IHasOptions { constructor(opts: TextareaOptions); - + /** * Original options object. */ options: TextareaOptions; - + /** * The input text. read-only. */ value: string; - + /** * Submit the textarea (emits submit). */ @@ -2101,32 +2101,32 @@ declare namespace Blessed { */ cancel(): void; /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives + * Grab key events and start reading text from the keyboard. Takes a callback which receives * the final value. */ readInput(callback?: (err: any, value?: string) => void): void; /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives + * Grab key events and start reading text from the keyboard. Takes a callback which receives * the final value. */ input(callback: (err: any, value?: string) => void): void; /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives + * Grab key events and start reading text from the keyboard. Takes a callback which receives * the final value. */ setInput(callback: (err: any, value?: string) => void): void; /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which * receives the final value. */ readEditor(callback: (err: any, value?: string) => void): void; /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which * receives the final value. */ editor(callback: (err: any, value?: string) => void): void; /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which * receives the final value. */ setEditor(callback: (err: any, value?: string) => void): void; @@ -2142,9 +2142,9 @@ declare namespace Blessed { * Set value. */ setValue(text: string): void; - + // ** events ** // - + on(event: string, listener: Function): this; on(event: "error", callback: (err: any) => void): this; @@ -2162,7 +2162,7 @@ declare namespace Blessed { */ on(event: "action", callback: (value: any) => void): this; } - + export interface TextboxOptions extends TextareaOptions { /** * Completely hide text. @@ -2173,10 +2173,10 @@ declare namespace Blessed { */ censor?: boolean; } - + export class TextboxElement extends TextareaElement implements IHasOptions { constructor(opts: TextboxOptions); - + /** * Original options object. */ @@ -2189,14 +2189,14 @@ declare namespace Blessed { /** * Replace text with asterisks (*). */ - censor: boolean; + censor: boolean; } - + export interface ButtonOptions extends BoxOptions { } export class ButtonElement extends InputElement implements IHasOptions { constructor(opts: ButtonOptions); - + /** * Original options object. */ @@ -2206,25 +2206,25 @@ declare namespace Blessed { * Press button. Emits press. */ press(): void; - + on(event: string, listener: Function): this; on(event: "press", callback: () => void): this; } - + export interface CheckboxOptions extends BoxOptions { - /** - * whether the element is checked or not. + /** + * whether the element is checked or not. * */ checked?: boolean; - /** - * enable mouse support. + /** + * enable mouse support. * */ mouse?: boolean; } - - /** - * A checkbox which can be used in a form element. + + /** + * A checkbox which can be used in a form element. * */ export class CheckboxElement extends InputElement implements IHasOptions { constructor(options?: CheckboxOptions); @@ -2234,39 +2234,39 @@ declare namespace Blessed { */ options: CheckboxOptions; - /** - * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). * */ text: string; - /** - * whether the element is checked or not. + /** + * whether the element is checked or not. * */ checked: boolean; - /** - * same as `checked`. + /** + * same as `checked`. * */ value: boolean; - /** - * check the element. + /** + * check the element. * */ check(): void; - /** - * uncheck the element. + /** + * uncheck the element. * */ uncheck(): void; - /** - * toggle checked state. + /** + * toggle checked state. * */ toggle(): void; - } + } export interface RadioSetOptions extends BoxOptions { } /** - * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive * with each other. - * */ + * */ export abstract class RadioSetElement extends BoxElement { constructor(opts: RadioSetOptions); } @@ -2279,7 +2279,7 @@ declare namespace Blessed { export abstract class RadioButtonElement extends CheckboxElement { constructor(opts: RadioButtonOptions); } - + export interface PromptOptions extends BoxOptions { } /** @@ -2297,7 +2297,7 @@ declare namespace Blessed { setInput(text: string, value: string, callback: (err: any, value: string) => void): void; readInput(text: string, value: string, callback: (err: any, value: string) => void): void; } - + export interface QuestionOptions extends BoxOptions { } /** @@ -2307,13 +2307,13 @@ declare namespace Blessed { constructor(opts: QuestionOptions); options: QuestionOptions; - + /** * Ask a question. callback will yield the result. */ ask(question: string, callback: (err: any, value: string) => void): void; } - + export interface MessageOptions extends BoxOptions { } /** @@ -2331,14 +2331,14 @@ declare namespace Blessed { log(text: string, callback: (err: any) => void): void; display(text: string, time: number, callback: (err: any) => void): void; display(text: string, callback: (err: any) => void): void; - + /** * Display an error in the same way. */ error(text: string, time: number, callback: () => void): void; error(text: string, callback: () => void): void; } - + export interface LoadingOptions extends BoxOptions { } /** @@ -2360,32 +2360,32 @@ declare namespace Blessed { } export interface ProgressBarOptions extends BoxOptions { - /** - * can be `horizontal` or `vertical`. + /** + * can be `horizontal` or `vertical`. * */ orientation: string; - /** - * the character to fill the bar with (default is space). + /** + * the character to fill the bar with (default is space). * */ pch: string; - /** - * the amount filled (0 - 100). + /** + * the amount filled (0 - 100). * */ filled: number; - /** - * same as `filled`. + /** + * same as `filled`. * */ value: number; - /** - * enable key support. + /** + * enable key support. * */ keys: boolean; - /** - * enable mouse support. + /** + * enable mouse support. * */ mouse: boolean; } - + /** * A progress bar allowing various styles. This can also be used as a form input. */ @@ -2394,19 +2394,19 @@ declare namespace Blessed { options: ProgressBarOptions; - /** - * progress the bar by a fill amount. + /** + * progress the bar by a fill amount. * */ progress(amount:number): void; - /** - * set progress to specific amount. + /** + * set progress to specific amount. * */ setProgress(amount:number): void; - /** - * reset the bar. + /** + * reset the bar. * */ reset(): void; - + on(event: string, listener: Function): this; /** * Bar was reset. @@ -2419,104 +2419,104 @@ declare namespace Blessed { } export interface LogOptions extends ScrollableTextOptions { - /** - * amount of scrollback allowed. default: Infinity. + /** + * amount of scrollback allowed. default: Infinity. * */ scrollback?: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. + /** + * scroll to bottom on input even if the user has scrolled up. default: false. * */ scrollOnInput?: boolean; } - - /** - * A log permanently scrolled to the bottom. + + /** + * A log permanently scrolled to the bottom. * */ export class Log extends ScrollableTextElement implements IHasOptions { constructor(options?: LogOptions); options: LogOptions; - /** - * amount of scrollback allowed. default: Infinity. + /** + * amount of scrollback allowed. default: Infinity. * */ scrollback: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. + /** + * scroll to bottom on input even if the user has scrolled up. default: false. * */ scrollOnInput: boolean; - /** - * add a log line. + /** + * add a log line. * */ log(text:string): void; - /** - * add a log line. + /** + * add a log line. * */ add(text:string): void; } export interface TableOptions extends BoxOptions { - /** - * array of array of strings representing rows (same as `data`). + /** + * array of array of strings representing rows (same as `data`). * */ rows?: string[][]; - /** - * array of array of strings representing rows (same as `rows`). + /** + * array of array of strings representing rows (same as `rows`). * */ data?: string[][]; - /** - * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). * */ pad?: number; - /** - * do not draw inner cells. + /** + * do not draw inner cells. * */ noCellBorders?: boolean; - /** - * fill cell borders with the adjacent background color. + /** + * fill cell borders with the adjacent background color. * */ fillCellBorders?: boolean; } - /** - * A stylized table of text elements. - * */ + /** + * A stylized table of text elements. + * */ export class TableElement extends BoxElement implements IHasOptions { constructor(opts: TableOptions); options: TableOptions; - /** - * set rows in table. array of arrays of strings. + /** + * set rows in table. array of arrays of strings. * */ setData(rows: string[][]): void; - /** - * set rows in table. array of arrays of strings. + /** + * set rows in table. array of arrays of strings. * */ setRows(rows: string[][]): void; } export interface TerminalOptions extends BoxOptions { - /** - * handler for input data. + /** + * handler for input data. * */ handler?: (userInput:Buffer) => void; - /** - * name of shell. $SHELL by default. + /** + * name of shell. $SHELL by default. * */ shell?:string; - /** - * args for shell. + /** + * args for shell. * */ args?:any; - /** - * can be line, underline, and block. + /** + * can be line, underline, and block. * */ cursor?: 'line'|'underline'|'block'; - + terminal?: string; - + /** * Object for process env. */ @@ -2528,39 +2528,39 @@ declare namespace Blessed { options: TerminalOptions; - /** + /** * reference to the headless term.js terminal. * */ term: any; - /** - * reference to the pty.js pseudo terminal. + /** + * reference to the pty.js pseudo terminal. * */ pty: any; - /** - * write data to the terminal. + /** + * write data to the terminal. * */ write(data:string): void; - /** - * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. * */ screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; } export interface ImageOptions extends BoxOptions { - /** - * path to image. + /** + * path to image. * */ file: string; - /** - * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. * */ type: "ansi" | "overlay" | "w3m"; } - - /** - * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. * */ export class ImageElement extends BoxElement implements IHasOptions { constructor(options?: ImageOptions); @@ -2569,44 +2569,44 @@ declare namespace Blessed { } export interface ANSIImageOptions extends BoxOptions { - /** - * URL or path to PNG/GIF file. Can also be a buffer. + /** + * URL or path to PNG/GIF file. Can also be a buffer. * */ file: string; - /** - * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). * */ scale: number; /** * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. - * */ + * */ width: number | string; height: number | string; - + /** * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). */ ascii: string; - + /** * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). */ animate: boolean; - + /** * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) */ - speed: number; - + speed: number; + /** * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). */ optimization: "mem" | "cpu"; } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. * */ export class ANSIImageElement extends BoxElement implements IHasOptions { constructor(options?:ANSIImageOptions); @@ -2618,18 +2618,18 @@ declare namespace Blessed { */ img: Types.TImage; - /** - * set the image in the box to a new path. + /** + * set the image in the box to a new path. * */ setImage(img: string, callback: () => void): void; - /** - * clear the current image. + /** + * clear the current image. * */ clearImage(callback: () => void): void; /** * Play animation if it has been paused or stopped. */ - play(): void; + play(): void; /** * Pause animation. */ @@ -2644,7 +2644,7 @@ declare namespace Blessed { /** * Path to image. */ - file: string; + file: string; /** * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). */ @@ -2652,39 +2652,39 @@ declare namespace Blessed { /** * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; + w3m: string; /** * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). */ search: string; } - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. * */ export class OverlayImageElement extends BoxElement implements IHasOptions { constructor(options?: OverlayImageOptions); - + options: OverlayImageOptions; - /** - * set the image in the box to a new path. + /** + * set the image in the box to a new path. * */ setImage(img: string, callback: () => void): void; - /** - * clear the current image. + /** + * clear the current image. * */ clearImage(callback: () => void): void; - /** - * get the size of an image file in pixels. + /** + * get the size of an image file in pixels. * */ imageSize(img:string, callback: () => void): void; - /** - * get the size of the terminal in pixels. + /** + * get the size of the terminal in pixels. * */ termSize(callback: () => void): void; - /** - * get the pixel to cell ratio for the terminal. + /** + * get the pixel to cell ratio for the terminal. * */ getPixelRatio(callback: () => void): void; } @@ -2697,30 +2697,30 @@ declare namespace Blessed { /** * Start time in seconds. */ - start: number; + start: number; } - + export class VideoElement extends BoxElement implements IHasOptions { constructor(options?: VideoOptions); options: VideoOptions; - + /** * The terminal element running mplayer or mpv. */ tty: any; } - + export interface LayoutOptions extends ElementOptions { /** - * A callback which is called right before the children are iterated over to be rendered. Should return an + * A callback which is called right before the children are iterated over to be rendered. Should return an * iterator callback which is called on each child element: iterator(el, i). */ renderer?: () => void; /** - * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render - * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' * width and height are always determined by the largest children in the layout. */ layout: "inline" | "inline-block" | "grid"; @@ -2732,25 +2732,25 @@ declare namespace Blessed { options: LayoutOptions; /** - * A callback which is called right before the children are iterated over to be rendered. Should return an + * A callback which is called right before the children are iterated over to be rendered. Should return an * iterator callback which is called on each child element: iterator(el, i). */ renderer(coords: PositionCoords): void; /** - * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful * for checking child elements that have already been attempted to be rendered! see the example below. */ isRendered(el: BlessedElement): boolean; /** - * Get the last rendered and visible child element based on an index. This is useful for basing the position + * Get the last rendered and visible child element based on an index. This is useful for basing the position * of the current child element on the position of the last child element. */ getLast(i: number): Element; /** - * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position * of the current child element on the position of the last child element. See the example below. */ - getLastCoords(i: number): PositionCoords; + getLastCoords(i: number): PositionCoords; } export class Program { @@ -2816,21 +2816,21 @@ declare namespace Blessed { export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; export function table(options?: Widgets.TableOptions): Widgets.TableElement; - + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; - + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; - + export function escape(item: any): any; export const colors: { match: (hexColor: string) => string } } -export = Blessed; \ No newline at end of file +export = Blessed; diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index e9a79d8834..cceb0ebc54 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -726,7 +726,28 @@ declare namespace Bluebird { * * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. */ - export class AggregateError extends Error {} + export class AggregateError extends Error implements ArrayLike { + length: number; + [index: number]: Error; + join(separator?: string): string; + pop(): Error; + push(...errors: Error[]): number; + shift(): Error; + unshift(...errors: Error[]): number; + slice(begin?: number, end?: number): AggregateError; + filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError; + forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined; + some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean; + every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean; + map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError; + indexOf(searchElement: Error, fromIndex?: number): number; + lastIndexOf(searchElement: Error, fromIndex?: number): number; + reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any; + reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any; + sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError; + reverse(): AggregateError; + } + /** * returned by `Bluebird.disposer()`. diff --git a/types/bonjour/bonjour-tests.ts b/types/bonjour/bonjour-tests.ts index 1ae8a218fe..61e7373f01 100644 --- a/types/bonjour/bonjour-tests.ts +++ b/types/bonjour/bonjour-tests.ts @@ -1,20 +1,23 @@ import * as bonjour from 'bonjour'; -var bonjourOptions: bonjour.BonjourOptions; -var bonjourInstance: bonjour.Bonjour; +let bonjourOptions: bonjour.BonjourOptions; +let bonjourInstance: bonjour.Bonjour; -var serviceOptions: bonjour.ServiceOptions; -var service: bonjour.Service; +let serviceOptions: bonjour.ServiceOptions; +let service: bonjour.Service; -var browserOptions: bonjour.BrowserOptions; -var browser: bonjour.Browser; +let browserOptions: bonjour.BrowserOptions; +let browser: bonjour.Browser; -bonjourOptions = { interface: '192.168.1.1', port: 5353 }; -bonjourInstance = new bonjour.Bonjour(bonjourOptions); +bonjourOptions = {}; +bonjourInstance = bonjour(bonjourOptions); -serviceOptions = { name: 'My Web Server', type: 'http', port: 3000 }; +// Publish a dummy server under name 'My Website' type http port 3000 +serviceOptions = { name: 'My Website', type: 'http', port: 3000 }; service = bonjourInstance.publish(serviceOptions); browserOptions = { protocol: 'tcp', type: 'http' }; -browser = bonjour.find(browserOptions); - +// Look for the server +browser = bonjourInstance.findOne(browserOptions, (srv: bonjour.Service) => { + // You can test here if the found server (srv) name is 'My Website' +}); diff --git a/types/bonjour/index.d.ts b/types/bonjour/index.d.ts index 0eb5b584c0..bba5debb3c 100644 --- a/types/bonjour/index.d.ts +++ b/types/bonjour/index.d.ts @@ -1,68 +1,82 @@ -// Type definitions for bonjour v3.5.0 +// Type definitions for bonjour 3.5 // Project: https://github.com/watson/bonjour -// Definitions by: Quentin Lampin +// Definitions by: Quentin Lampin , Nicolas Voigt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// -export interface BonjourOptions { - multicast?: boolean; - interface?: string; - port?: number; - ip?: string; - ttl?: number; - loopback?: boolean; - reuseAddr?: boolean; +declare function bonjour(opts?: bonjour.BonjourOptions): bonjour.Bonjour; +export = bonjour; +declare namespace bonjour { + /** + * Start a browser + * + * The browser listens for services by querying for PTR records of a given + * type, protocol and domain, e.g. _http._tcp.local. + * + * If no type is given, a wild card search is performed. + * + * An internal list of online services is kept which starts out empty. When + * ever a new service is discovered, it's added to the list and an "up" event + * is emitted with that service. When it's discovered that the service is no + * longer available, it is removed from the list and a "down" event is emitted + * with that service. + */ + interface Browser extends NodeJS.EventEmitter { + services: Service[]; + start(): void; + update(): void; + stop(): void; + on(event: 'up' | 'down', listener: (service: Service) => void): this; + once(event: 'up' | 'down', listener: (service: Service) => void): this; + removeListener(event: 'up' | 'down', listener: (service: Service) => void): this; + removeAllListeners(event: 'up' | 'down'): this; + } + interface BrowserOptions { + type?: string; + subtypes?: string[]; + protocol?: string; + txt?: Object; + } + + interface ServiceOptions { + name: string; + host?: string; + port: number; + type: string; + subtypes?: string[]; + protocol?: 'udp'|'tcp'; + txt?: Object; + } + + interface Service extends NodeJS.EventEmitter { + name: string; + type: string; + subtypes: string[]; + protocol: string; + host: string; + port: number; + fqdn: string; + txt: Object; + published: boolean; + + stop(cb: () => any): void; + start(): void; + } + interface BonjourOptions { + multicast?: boolean; + interface?: string; + port?: number; + ip?: string; + ttl?: number; + loopback?: boolean; + reuseAddr?: boolean; + } + interface Bonjour { + (opts?: BonjourOptions): Bonjour; + publish(options: ServiceOptions): Service; + unpublishAll(cb?: () => void): void; + find(options: BrowserOptions, onUp?: (service: Service) => void): Browser; + findOne(options: BrowserOptions, cb?: (service: Service) => void): Browser; + destroy(): void; + } } - -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/types/bonjour/tslint.json b/types/bonjour/tslint.json new file mode 100644 index 0000000000..a62d0d4e68 --- /dev/null +++ b/types/bonjour/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false + } +} diff --git a/types/bookshelf/bookshelf-tests.ts b/types/bookshelf/bookshelf-tests.ts index 61718a4274..f42a1bf784 100644 --- a/types/bookshelf/bookshelf-tests.ts +++ b/types/bookshelf/bookshelf-tests.ts @@ -481,6 +481,15 @@ new Book({'ISBN-13': '9780440180296'}) /* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */ +{ + (new User).fetchAll({ + columns: ['id', 'name'], + withRelated: ['posts.tags'] + }).then((user: any) => { + console.log(user); + }) +} + /* model.format(), see http://bookshelfjs.org/#Model-instance-format */ /* model.get(), see http://bookshelfjs.org/#Model-instance-get */ @@ -637,6 +646,16 @@ customer.on('fetching', (model, columns) => { /* model.once(), see http://bookshelfjs.org/#Model-instance-once */ +/* model.orderBy(), see http://bookshelfjs.org/#Model-instance-orderBy */ +{ + (new User) + .orderBy('name', 'ASC') + .fetchAll() + .then((users: Bookshelf.Collection) => { + console.log(users) + }); +} + /* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */ // Example of a "parse" to convert snake_case to camelCase, using `underscore.string` @@ -1096,6 +1115,16 @@ ships.on('fetched', (collection, response) => { /* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */ +/* collection.orderBy(), see http://bookshelfjs.org/#Collection-instance-orderBy */ +{ + User.collection() + .orderBy('-name') + .fetch() + .then((users: Bookshelf.Collection) => { + console.log(users); + }) +} + /* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */ /* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */ @@ -1376,4 +1405,4 @@ new User({name: 'John'}).fetchAll({require: true}) new Country({id: 1}).capital().fetch().then(model => { // ... }); -} \ No newline at end of file +} diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index 398534806d..86176ed2e8 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for bookshelfjs v0.8.2 +// Type definitions for bookshelfjs v0.9.3 // Project: http://bookshelfjs.org/ -// Definitions by: Andrew Schurman +// Definitions by: Andrew Schurman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,6 +23,8 @@ interface Bookshelf extends Bookshelf.Events { declare function Bookshelf(knex: knex): Bookshelf; declare namespace Bookshelf { + type SortOrder = 'ASC'|'asc'|'DESC'|'desc'; + abstract class Events { on(event?: string, callback?: EventFunction, context?: any): void; off(event?: string): void; @@ -105,6 +107,7 @@ declare namespace Bookshelf { morphOne>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R; morphTo(name: string, columnNames?: string[], ...target: typeof Model[]): T; morphTo(name: string, ...target: typeof Model[]): T; + orderBy(column: string, order?: SortOrder): T; // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) query(): Knex.QueryBuilder; @@ -242,6 +245,7 @@ declare namespace Bookshelf { detach(options?: SyncOptions): BlueBird; fetchOne(options?: CollectionFetchOneOptions): BlueBird; load(relations: string | string[], options?: SyncOptions): BlueBird>; + orderBy(column: string, order?: SortOrder): T; // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) query(): Knex.QueryBuilder; @@ -278,8 +282,7 @@ declare namespace Bookshelf { [index: string]: (query: Knex.QueryBuilder) => Knex.QueryBuilder; } - interface FetchAllOptions extends SyncOptions { - require?: boolean; + interface FetchAllOptions extends FetchOptions { } interface SaveOptions extends SyncOptions { diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index bb2f5e4bc0..4d9d0b3a5b 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Igor Rogatty , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - export = Boom; declare namespace Boom { diff --git a/types/boom/tsconfig.json b/types/boom/tsconfig.json index d64d51130b..c3bee46396 100644 --- a/types/boom/tsconfig.json +++ b/types/boom/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/bootstrap.v3.datetimepicker/index.d.ts b/types/bootstrap.v3.datetimepicker/index.d.ts index 4686aa9680..f37a42b67d 100644 --- a/types/bootstrap.v3.datetimepicker/index.d.ts +++ b/types/bootstrap.v3.datetimepicker/index.d.ts @@ -337,16 +337,16 @@ export interface DatetimepickerOptions { /** Shows the week of the year to the left of first day of the week. * @default: false */ - calendarWeeks?: boolean; + calendarWeeks?: boolean; /** Using a Bootstraps collapse to switch between date/time pickers. * @default: true */ - collapse?: boolean; + collapse?: boolean; /** Disables the section of days of the week, e.g. weekends. * Accepts: array of numbers from 0-6 * @default: false */ - daysOfWeekDisabled?: number[] | boolean; + daysOfWeekDisabled?: number[] | boolean; /** Changes the heading of the datepicker when in "days" view. * @default: "MMMM YYYY" */ @@ -358,14 +358,14 @@ export interface DatetimepickerOptions { /** Sets the picker default date/time. Overrides useCurrent * @default: false */ - defaultDate?: boolean | moment.Moment | Date | string; + defaultDate?: boolean | moment.Moment | Date | string; /** Disables selection of dates in the array, e.g. holidays * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. * eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true } * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 */ - disabledDates?: boolean | Array | any; + disabledDates?: boolean | Array | any; /** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. @@ -384,7 +384,7 @@ export interface DatetimepickerOptions { * eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true } * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 */ - enabledDates?: boolean | Array | any; + enabledDates?: boolean | Array | any; /** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. @@ -403,17 +403,17 @@ export interface DatetimepickerOptions { /** See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. * @default: false */ - format?: boolean | string | moment.MomentBuiltinFormat; + format?: boolean | string | moment.MomentBuiltinFormat; /** Change the default icons for the pickers functions. */ - icons?: Icons; + icons?: Icons; /** Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. * @default: false */ - ignoreReadonly?: boolean; + ignoreReadonly?: boolean; /** Will display the picker inline without the need of a input field. This will also hide borders and shadows. * @default: false */ - inline?: boolean; + inline?: boolean; /** Allows for custom events to fire on keyboard press. * eg: keybinds: { * up: (widget) => console.log(widget), @@ -433,17 +433,17 @@ export interface DatetimepickerOptions { /** See momentjs for valid locales. You must include moment-with-locales.js or a local js file. * @default: moment.locale() */ - locale?: string; + locale?: string; /** Prevents date/time selections after this date. * maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. * @default: false */ - maxDate?: boolean | moment.Moment | Date | string; + maxDate?: boolean | moment.Moment | Date | string; /** Prevents date/time selections before this date. * minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. * @default: false */ - minDate?: boolean | moment.Moment | Date | string; + minDate?: boolean | moment.Moment | Date | string; /** Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} */ @@ -452,7 +452,7 @@ export interface DatetimepickerOptions { * Clicking the "Clear" button will set the calendar to null. * @default: false */ - showClear?: boolean; + showClear?: boolean; /** Show the "Close" button in the icon toolbar. * Clicking the "Close" button will call hide() * @default: false @@ -462,11 +462,11 @@ export interface DatetimepickerOptions { * Clicking the "Today" button will set the calendar view and set the date to now. * @default: false */ - showTodayButton?: boolean; + showTodayButton?: boolean; /** Shows the picker side by side when using the time and date together. * @default: false */ - sideBySide?: boolean; + sideBySide?: boolean; /** Number of minutes the up/down arrow's will move the minutes value in the time picker * @default: 1 */ @@ -479,17 +479,17 @@ export interface DatetimepickerOptions { /** Changes the placement of the icon toolbar. * @default: "default" */ - toolbarPlacement?: "default" | "top" | "bottom"; + toolbarPlacement?: "default" | "top" | "bottom"; /** This will change the tooltips over each icon to a custom string */ tooltips?: Tooltips; /** On show, will set the picker to the current date/time * @default: true */ - useCurrent?: boolean; + useCurrent?: boolean; /** Defines if moment should use strict date parsing when considering a date to be valid * @default: false */ - useStrict?: boolean; + useStrict?: boolean; /** This will change the viewDate without changing or setting the selected date. * @default: false */ @@ -498,7 +498,7 @@ export interface DatetimepickerOptions { * Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY * @default: "days" */ - viewMode?: "decades" | "years" | "months" | "days"; + viewMode?: "decades" | "years" | "months" | "days"; /** On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" * @default: null */ @@ -520,7 +520,7 @@ export interface Icons { /** default: "glyphicon glyphicon-screenshot" */ previous?: string; /** default: "glyphicon glyphicon-chevron-right" */ - time?: string; + time?: string; /** default: "glyphicon glyphicon-chevron-down" */ today?: string; /** default: "glyphicon glyphicon-chevron-up" */ diff --git a/types/braintree-web/index.d.ts b/types/braintree-web/index.d.ts index a30a880684..46f16e072b 100644 --- a/types/braintree-web/index.d.ts +++ b/types/braintree-web/index.d.ts @@ -1087,7 +1087,7 @@ declare namespace braintree { * }); * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame. */ - tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; + tokenize(options: { flow: string, intent?: string, offerCredit?: boolean, useraction?: string, amount?: (string | number), currency?: string, displayName?: string, locale?: string, enableShippingAddress?: boolean, shippingAddressOverride?: PayPalShippingAddress, shippingAddressEditable?: boolean, billingAgreementDescription?: string }, callback: callback): PayPalTokenizeReturn; /** * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}. diff --git a/types/capitalize/capitalize-tests.ts b/types/capitalize/capitalize-tests.ts new file mode 100644 index 0000000000..5e74a594d0 --- /dev/null +++ b/types/capitalize/capitalize-tests.ts @@ -0,0 +1,12 @@ +import * as capitalize from "capitalize"; +import { words } from "capitalize"; + +capitalize("united states"); + +capitalize.words("united states"); + +capitalize.words('hello-cañapolísas'); + +capitalize.words("it's a nice day"); + +words("united states"); diff --git a/types/capitalize/index.d.ts b/types/capitalize/index.d.ts new file mode 100644 index 0000000000..b844784757 --- /dev/null +++ b/types/capitalize/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for capitalize 1.0 +// Project: https://github.com/grncdr/js-capitalize +// Definitions by: Frederick Fogerty +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Capitalize the first letter of a string + * @param input the string to capitalize + */ +declare function capitalize(input: string): string; +declare namespace capitalize { + /** + * Capitalize each word in a string + * @param input the string to capitalize + */ + function words(input: string): string; +} +export = capitalize; diff --git a/types/capitalize/tsconfig.json b/types/capitalize/tsconfig.json new file mode 100644 index 0000000000..d196ac1315 --- /dev/null +++ b/types/capitalize/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "capitalize-tests.ts" + ] +} \ No newline at end of file diff --git a/types/capitalize/tslint.json b/types/capitalize/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/capitalize/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts new file mode 100644 index 0000000000..e832f58446 --- /dev/null +++ b/types/catbox/index.d.ts @@ -0,0 +1,247 @@ +// Type definitions for catbox 7.1 +// Project: https://github.com/hapijs/catbox +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Boom from 'boom'; + +export interface CallBackNoResult { + (err?: Boom.BoomError): void; +} +export interface CallBackWithResult { + (err: Boom.BoomError | null | undefined, result: T): void; +} + +/** + * Client + * The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where: + * engine - is an object or a prototype function implementing the cache strategy: + * * function - a prototype function with the signature function(options). catbox will call new func(options). + * * object - a pre instantiated client implementation object. Does not support passing options. + * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * @see {@link https://github.com/hapijs/catbox#client} + */ +export interface Client extends ClientApi { + new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +} + +type EnginePrototypeOrObject = EnginePrototype | ClientApi; + +/** + * A prototype CatBox engine function + */ +export interface EnginePrototype { + new(settings: ClientOptions): ClientApi; +} + +/** + * Client API + * The Client object provides the following methods: + * @see {@link https://github.com/hapijs/catbox#api} + */ +export interface ClientApi { + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; +} + +/** + * Any method with a key argument takes an object with the following required properties: + */ +export interface CacheKey { + /** segment - a caching segment name string. Enables using a single cache server for storing different sets of items with overlapping ids. */ + segment: string; + /** id - a unique item identifier string (per segment). Can be an empty string. */ + id: string; +} + +/** Cached object contains the following: */ +export interface CachedObject { + /** item - the value stored in the cache using set(). */ + item: any; + /** stored - the timestamp when the item was stored in the cache (in milliseconds). */ + stored: number; + /** ttl - the remaining time-to-live (not the original value used when storing the object). */ + ttl: number; +} + +type CacheItem = any; + +export interface ClientOptions { + partition: string; +} + +/** + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * * options - an object with the IPolicyOptions structure + * * cache - a Client instance (which has already been started). + * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export interface Policy extends PolicyAPI { + new(options: PolicyOptions, cache: Client, segment: string): Policy; +} + +/** + * Policy API + * The Policy object provides the following methods: + * @see {@link https://github.com/hapijs/catbox#api-1} + */ +export interface PolicyAPI { + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; +} + +/** + * The return function. The function signature is function(err, value, cached, report) where: + * @param err - any errors encountered. + * @param value - the fetched or generated value. + * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions + * @param report - an object with logging information about the generation operation + */ +export interface PolicyGetCallback{ + (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; +} + +export interface PolicyGetCallbackCachedOptions { + /** item - the cached value. */ + item: CacheItem; + /** stored - the timestamp when the item was stored in the cache. */ + stored: number; + /** ttl - the cache ttl value for the record. */ + ttl: number; + /** isStale - true if the item is stale. */ + isStale: boolean; +} + +/** + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export interface PolicyOptions { + /** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */ + expiresAt?: string; + /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ + generateFunc?: GenerateFunc; + /** + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * * stored - the timestamp when the item was stored in the cache (in milliseconds). + * * ttl - the remaining time-to-live (not the original value used when storing the object). + */ + staleIn?: number | ((stored: number, ttl: number) => number); + /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ + staleTimeout?: number; + /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + generateTimeout?: number | false; + /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ + dropOnError?: boolean; + /** generateOnReadError - if false, an upstream cache read error will stop the get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */ + generateOnReadError?: boolean; + /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ + generateIgnoreWriteError?: boolean; + /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + pendingGenerateTimeout?: number; +} + +/** + * generateFunc + * Is used in PolicyOptions + * A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) + * @param id - the id string or object provided to the get() method. + * @param next - the method called when the new item is returned with the signature function(err, value, ttl) where: + * * err - an error condition. + * * value - the new value generated. + * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export interface GenerateFunc { + (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; +} + +/** + * An object with logging information about the generation operation containing the following keys (as relevant): + */ +export interface PolicyGetCallbackReportLog { + /** msec - the cache lookup time in milliseconds. */ + msec: number; + /** stored - the timestamp when the item was stored in the cache. */ + stored: number; + /** isStale - true if the item is stale. */ + isStale: boolean; + /** ttl - the cache ttl value for the record. */ + ttl: number; + /** error - lookup error. */ + error?: Boom.BoomError; +} + +/** + * an object with cache statistics where: + */ +export interface CacheStatisticsObject { + /** sets - number of cache writes. */ + sets: number; + /** gets - number of cache get() requests. */ + gets: number; + /** hits - number of cache get() requests in which the requested id was found in the cache (can be stale). */ + hits: number; + /** stales - number of cache reads with stale requests (only counts the first request in a queued get() operation). */ + stales: number; + /** generates - number of calls to the generate function. */ + generates: number; + /** errors - cache operations errors. TODO check this*/ + errors: number; +} diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/catbox/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/chai-arrays/chai-arrays-tests.ts b/types/chai-arrays/chai-arrays-tests.ts new file mode 100644 index 0000000000..7fabaacbca --- /dev/null +++ b/types/chai-arrays/chai-arrays-tests.ts @@ -0,0 +1,76 @@ +import { expect } from 'chai'; +import { assert } from 'chai'; + +import chai = require('chai'); +import ChaiArrays = require('chai-arrays'); + +chai.use(ChaiArrays); +chai.should(); + +const arr: any[] = [1, 2, 3]; +const str: string = 'abcdef'; + +const otherArr: number[] = [1, 2, 3]; +const anotherArr: number[] = [2, 4]; +const yetAnotherArr: number[] = [8, 5, 7]; + +arr.should.be.array(); +str.should.not.be.array(); + +expect(arr).to.be.array(); +expect(str).not.to.be.array(); + +assert.array(arr, 'is array'); + +arr.should.be.ofSize(3); +arr.should.not.be.ofSize(4); + +expect(arr).to.be.ofSize(3); +expect(str).not.to.be.ofSize(4); + +assert.ofSize(arr, 3, 'has 3 elements'); + +arr.should.be.equalTo(otherArr); +arr.should.not.be.equalTo(anotherArr); + +expect(arr).to.be.equalTo(otherArr); +expect(str).to.be.not.equalTo(anotherArr); + +assert.equalTo(arr, otherArr, 'is equal to'); + +arr.should.be.containing(1); +arr.should.not.be.containing(4); + +expect(arr).to.be.containing(1); +expect(str).to.be.not.containing(4); + +assert.containing(arr, 1, 'contains'); + +arr.should.be.containingAllOf(otherArr); +arr.should.not.be.containingAllOf(anotherArr); + +expect(arr).to.be.containingAllOf(otherArr); +expect(str).to.be.not.containingAllOf(anotherArr); + +assert.containingAllOf(arr, otherArr, 'contains all of'); + +arr.should.be.containingAnyOf(otherArr); +arr.should.be.containingAnyOf(anotherArr); +arr.should.not.be.containingAnyOf(yetAnotherArr); + +expect(arr).to.be.containingAnyOf(otherArr); +expect(str).to.be.containingAnyOf(anotherArr); +expect(str).to.be.not.containingAnyOf(yetAnotherArr); + +assert.containingAnyOf(arr, otherArr, 'contains any of'); +assert.containingAnyOf(arr, anotherArr, 'contains any of'); + +arr.should.be.sorted(); +anotherArr.should.be.sorted(); +yetAnotherArr.should.be.sorted(); + +expect(arr).to.be.sorted(); +expect(anotherArr).to.be.sorted(); +expect(yetAnotherArr).to.be.not.sorted(); + +assert.sorted(arr, 'sorted'); diff --git a/types/chai-arrays/index.d.ts b/types/chai-arrays/index.d.ts new file mode 100644 index 0000000000..d387d1614d --- /dev/null +++ b/types/chai-arrays/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for chai-arrays 1.0 +// Project: https://github.com/GaneshSPatil/chai-arrays +// Definitions by: Clément Prévot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace Chai { + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + array(): Assertion; + ofSize(size: number): Assertion; + equalTo(arr: any[]): Assertion; + containing(value: any): Assertion; + containingAllOf(values: any[]): Assertion; + containingAnyOf(values: any[]): Assertion; + sorted(): Assertion; + } + + interface Assert { + array(val: any[], msg?: string): void; + ofSize(val: any[], size: number, msg?: string): void; + equalTo(val: any[], array: any[], msg?: string): void; + containing(val: any[], value: any, msg?: string): void; + containingAllOf(val: any[], values: any[], msg?: string): void; + containingAnyOf(val: any[], values: any[], msg?: string): void; + sorted(val: any[], msg?: string): void; + } + } + + interface Array { + should: Chai.Assertion; + } +} + +declare function chaiArrays(chai: any, utils: any): void; +export = chaiArrays; diff --git a/types/chai-arrays/tsconfig.json b/types/chai-arrays/tsconfig.json new file mode 100644 index 0000000000..a555dfb8e2 --- /dev/null +++ b/types/chai-arrays/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chai-arrays-tests.ts" + ] +} diff --git a/types/leaflet-markercluster/tslint.json b/types/chai-arrays/tslint.json similarity index 100% rename from types/leaflet-markercluster/tslint.json rename to types/chai-arrays/tslint.json diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 73f62290f5..7690fe49a7 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -848,7 +848,7 @@ declare namespace Chai { * @param regExp Potential expected message match. * @param message Message to display on error. */ - throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, regExp: RegExp, message?: string): void; /** * Asserts that function will throw an error that is an instance of constructor. diff --git a/types/chance/index.d.ts b/types/chance/index.d.ts index 10538b747c..fc5347e859 100644 --- a/types/chance/index.d.ts +++ b/types/chance/index.d.ts @@ -39,6 +39,7 @@ declare namespace Chance { // Person age(opts?: Options): number; + gender(): string; birthday(): Date; birthday(opts?: Options): Date|string; cpf(): string; diff --git a/types/chocolatechipjs/index.d.ts b/types/chocolatechipjs/index.d.ts index 0e33e087c3..4c1d49f6d1 100644 --- a/types/chocolatechipjs/index.d.ts +++ b/types/chocolatechipjs/index.d.ts @@ -438,7 +438,7 @@ interface ChocolateChipStatic { /** * Serialize */ - serialize(form: HTMLFormElement | ChocolateChipElementArray): string; + serialize(form: HTMLFormElement | ChocolateChipElementArray): string; /** * Grabs values from a form and converts them into a JSON object. @@ -862,7 +862,7 @@ interface ChocolateChipElementArray extends Array { * @param property The property to remove. * @return HTMLElement[] */ - removeProp(property: string): ChocolateChipElementArray; + removeProp(property: string): ChocolateChipElementArray; /** * Adds the specified class(es) to each of the set of matched elements. diff --git a/types/classnames/classnames-tests.ts b/types/classnames/classnames-tests.ts index 5c99df82eb..1938acb4f9 100644 --- a/types/classnames/classnames-tests.ts +++ b/types/classnames/classnames-tests.ts @@ -1,6 +1,7 @@ -import classNames = require('classnames') +import classNames = require('classnames'); +import * as classNames2 from 'classnames'; -classNames('foo', 'bar'); // => 'foo bar' +classNames2('foo', 'bar'); // => 'foo bar' classNames('foo', 'bar'); // => 'foo bar' classNames('foo', { bar: true }); // => 'foo bar' @@ -21,4 +22,4 @@ classNames(["foo", ["bar", {baz: true}]]); // => 'foo bar baz' classNames(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' // Supporting booleans is tricky since we should only support passing in false, which is ignored -//classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1' +// classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1' diff --git a/types/classnames/index.d.ts b/types/classnames/index.d.ts index 22d9803399..42352fc9b8 100644 --- a/types/classnames/index.d.ts +++ b/types/classnames/index.d.ts @@ -1,22 +1,25 @@ -// Type definitions for classnames +// Type definitions for classnames 2.2 // Project: https://github.com/JedWatson/classnames -// Definitions by: Dave Keen , Adi Dahiya , Jason Killian +// Definitions by: Dave Keen +// Adi Dahiya +// Jason Killian +// Sean Kelley +// Michal Adamczyk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; +type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; interface ClassDictionary { [id: string]: boolean | undefined | null; } -interface ClassArray extends Array { } +// This is the only way I found to break circular references between ClassArray and ClassValue +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +interface ClassArray extends Array { } // tslint:disable-line no-empty-interface -interface ClassNamesFn { - (...classes: ClassValue[]): string; -} +type ClassNamesFn = (...classes: ClassValue[]) => string; -declare var classNames: ClassNamesFn; +declare const classNames: ClassNamesFn; -declare module "classnames" { - export = classNames -} +export = classNames; +export as namespace classNames; diff --git a/types/classnames/tslint.json b/types/classnames/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/classnames/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index d0b2dd6511..9a74dc1e53 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -178,7 +178,7 @@ declare namespace CodeMirror { /** Remove a CSS class from a line.line can be a line handle or number. where should be one of "text", "background", or "wrap"(see addLineClass). class can be left off to remove all classes for the specified node, or be a string to remove only a specific class. */ - removeLineClass(line: any, where: string, class_: string): CodeMirror.LineHandle; + removeLineClass(line: any, where: string, class_?: string): CodeMirror.LineHandle; /** * Compute the line at the given pixel height. @@ -439,7 +439,7 @@ declare namespace CodeMirror { /** Replace the part of the document between from and to with the given string. from and to must be {line, ch} objects. to can be left off to simply insert the string at position from. */ - replaceRange(replacement: string, from: CodeMirror.Position, to?: CodeMirror.Position): void; + replaceRange(replacement: string, from: CodeMirror.Position, to?: CodeMirror.Position, origin?: string): void; /** Get the content of line n. */ getLine(n: number): string; diff --git a/types/color/color-tests.ts b/types/color/color-tests.ts index fb561d4ad1..7b1a48a945 100644 --- a/types/color/color-tests.ts +++ b/types/color/color-tests.ts @@ -59,3 +59,4 @@ var chain: Color.Color = color .opaquer(0) .rotate(0) .mix(colorOther, 0) + .hsl(); diff --git a/types/color/index.d.ts b/types/color/index.d.ts index 0b7b505c01..8d6016c7d8 100644 --- a/types/color/index.d.ts +++ b/types/color/index.d.ts @@ -67,6 +67,13 @@ declare namespace Color { hex(color: string): Color; hex(): string; rgb(): Color; + hsl(): Color; + hsv(): Color; + hwb(): Color; + hcg(): Color; + cmyk(): Color; + xyz(): Color; + lab(): Color; rgbNumber(): number; luminosity(): number; contrast(color: Color): number; @@ -85,6 +92,7 @@ declare namespace Color { opaquer(value: number): Color; rotate(value: number): Color; mix(color: Color, value?: number): Color; + hsl(): Color; } } diff --git a/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts new file mode 100644 index 0000000000..4597e2c39a --- /dev/null +++ b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts @@ -0,0 +1,43 @@ +/** + * Display Messenger + */ +NativeKeyboard.showMessenger({ + onSubmit: (text) => {}, + onKeyboardDidHide: () => {}, + onKeyboardDidShow: () => {}, + onKeyboardWillShow: () => {}, + onTextChanged: (text) => {}, + onKeyboardWillHide: () => {}, +}); + +/** + * Display Messenger Keyboard + */ +NativeKeyboard.showMessengerKeyboard( + () => {}, + () => {}); + +/** + * Hide Messenger + */ +NativeKeyboard.hideMessenger( + { animated: true}, + () => {}, + () => {}); + +NativeKeyboard.hideMessenger(); + +/** + * Hide Messenger Keyboard + */ +NativeKeyboard.hideMessengerKeyboard( + () => {}, + () => {}); + +/** + * Update Messenger Keyboard + */ +NativeKeyboard.updateMessenger( + {text: 'FooBar'}, + () => {}, + () => {}); diff --git a/types/cordova-plugin-native-keyboard/index.d.ts b/types/cordova-plugin-native-keyboard/index.d.ts new file mode 100644 index 0000000000..0f64199bd1 --- /dev/null +++ b/types/cordova-plugin-native-keyboard/index.d.ts @@ -0,0 +1,303 @@ +// Type definitions for cordova-plugin-native-keyboard 1.3 +// Project: https://github.com/EddyVerbruggen/cordova-plugin-native-keyboard#readme +// Definitions by: Daniel Brolli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface NativeKeyboard { + /** + * Show the messenger, the bare minimum which has to be passed to the function is + * the onSubmit callback + * @param options + */ + showMessenger( + options: NativeKeyboardShowOptions + ): void; + + /** + * It's likely your app only has 1 one page where you want to show the messenger, + * so you want to hide it when the user navigates away. You can choose to do this + * either animated (a quick slide down animation) or not. + * + * @param options + * @param onSuccess + * @param onError + */ + hideMessenger( + options?: NativeKeyboardHideOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; + + /** + * Show a previously hidden keyboard + * + * @param onSuccess + * @param onError + */ + showMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Hide the keyboard, but not the messenger bar + * + * @param onSuccess + * @param onError + */ + hideMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Manipulate the messenger while it's open. For instance if you want to + * update the text programmatically based on what the user typed (by responding to + * onTextChanged events). + * + * @param options + * @param onSuccess + * @param onError + */ + updateMessenger( + options: NativeKeyboardUpdateOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; +} + +interface NativeKeyboardUpdateOptions { + /** + * Replace the messenger's text by this. The current text remains if omitted. + */ + text?: string; + + /** + * Position the cursor anywhere in the text range. Defaults to the end of the text. + */ + caretIndex?: number; + + /** + * If false or omitted no changes to the keyboard state are made. + */ + showKeyboard?: boolean; +} + +interface NativeKeyboardHideOptions { + /** + * A boolean flag inidicating if the keyboard should be shown/hidden with an animation + */ + animated?: boolean; +} + +interface NativeKeyboardShowOptions { + /** + * Callback function, which is being called as soon as the user submits + * @param text + */ + onSubmit(text: string): void; + + /** + * Callback function which is being executed as soon as the keyboard will show + */ + onKeyboardWillShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did show + */ + onKeyboardDidShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard will hide + */ + onKeyboardWillHide?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did hide + */ + onKeyboardDidHide?(): void; + + /** + * Callback function which is being executed as soon as the entered text changes. Will + * return the new text + * + * @param text + */ + onTextChanged?(text: string): void; + + /** + * DOM element, which should be scrolled automatically + */ + autoscrollElement?: any; + + /** + * Boolean value indicating if the content should be scrolled to the end after the messenger is + * shown + */ + scrollToBottomAfterMessengerShows?: boolean; + + /** + * Boolean value indicating if the keyboard should be kept open after submitting the entered + * text + * + * Default: false + */ + keepOpenAfterSubmit?: boolean; + + /** + * Makes the messenger bar slide in from the bottom. + * + * Default: false + */ + animated?: boolean; + + /** + * Open the keyboard when showing the messenger. + * + * Default: false + */ + showKeyboard?: boolean; + + /** + * A text which will be in the messenger bar, when opening + */ + text?: string; + + /** + * The color of the typed text in HEX. + * + * Default: #444 + */ + textColor?: string; + + /** + * A placeholder which will be in the messenger bar, when opening and the input field is + * empty + */ + placeholder?: string; + + /** + * The color of the placeholder. + * + * Default: #ccc + */ + placeholderColor?: string; + + /** + * The background color of the messenger bar. + * + * Default: #F6F6F6 + */ + backgroundColor?: string; + + /** + * The background color of the textview. Looks nicest on Android + * if it's the same color as the backgroundColor property. + * + * Default: #F6F6F6 + */ + textViewBackgroundColor?: string; + + /** + * The border color of the textview. + * + * Default: #666666 + */ + textViewBorderColor?: string; + + /** + * Maximum amount of chars that can be entered + */ + maxChars?: number; + + /** + * Options are: "none", "split", "countdown", "countdownreversed". + * Note that if maxChars is set, "none" will still show a counter. + * + * Default: "none" + */ + counterStyle?: string; + + /** + * Options are: "default", "decimalpad", "phonepad", "numberpad", "namephonepad", + * "number", "email", "twitter", "url", "alphabet", "search", "ascii" + * + * Default: "default" + */ + type?: string; + + /** + * Options are: "light", "dark". + * + * Default: "default" + */ + appearance?: string; + + /** + * Disables things like the Emoji keyboard and the Predicive text entry bar + * + * Default: false + */ + secure?: boolean; + + /** + * The left button of the messenger bar + */ + leftButton?: LeftButtonOptions; + + /** + * The right button of the messenger bar + */ + rightButton?: ButtonOptions; +} + +interface ButtonOptions { + /** + * The type of the button. + * Either "text", "fontawesome" or "ionicon". + * + * Default: "text" + */ + type?: string; + + /** + * The value of the button. On "text" the string is used as label + * On fonatawesome or ionicon the icon name is used (e.g. fa-rocket) + * + * Default: "Send" + */ + value?: string; + + /** + * If type is "text" you can set this to either "normal", "bold" or "italic". + * + * Default: "normal" + */ + textStyle?: string; + + /** + * The color of the button in HEX + * + * Default: #000 + */ + color: string; + + /** + * A callback being executed as soon as the button is clicked + */ + onPress(): void; +} + +interface LeftButtonOptions extends ButtonOptions { + /** + * Set to true to disable the button once text has been entered. + * + * Default: false + */ + disabledWhenTextEntered?: boolean; +} + +/** NativeKeyboard instance */ +declare var NativeKeyboard: NativeKeyboard; +interface Window { + NativeKeyboard: NativeKeyboard; +} diff --git a/types/cordova-plugin-native-keyboard/tsconfig.json b/types/cordova-plugin-native-keyboard/tsconfig.json new file mode 100644 index 0000000000..4309b2406b --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-native-keyboard-tests.ts" + ] +} diff --git a/types/cordova-plugin-native-keyboard/tslint.json b/types/cordova-plugin-native-keyboard/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts b/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts index 009b0b7d2b..fe14bae63c 100644 --- a/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts +++ b/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts @@ -3,7 +3,7 @@ var QRScanner: QRScanner = window.QRScanner; QRScanner.prepare(); QRScanner.prepare((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; }); -QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: String = results; }); +QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: string = results; }); QRScanner.cancelScan(); QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; }); QRScanner.show(); @@ -31,12 +31,12 @@ QRScanner.destroy((status) => {var obj: QRScannerStatus = status; }); QRScanner.prepare((err, status) => { var error: QRScannerError = err; - var num: Number = error.code; - var str: String = error.name; + var num: number = error.code; + var str: string = error.name; str = error._message; var obj: QRScannerStatus = status; - var bool: Boolean = status.authorized; + var bool: boolean = status.authorized; bool = status.denied; bool = status.restricted; bool = status.prepared; @@ -46,5 +46,5 @@ QRScanner.prepare((err, status) => { bool = status.lightEnabled; bool = status.canOpenSettings; bool = status.canEnableLight; - var num: Number = status.currentCamera; + var num: number = status.currentCamera; }); diff --git a/types/cordova-plugin-qrscanner/index.d.ts b/types/cordova-plugin-qrscanner/index.d.ts index ed5f72f26f..0f2a498a9c 100644 --- a/types/cordova-plugin-qrscanner/index.d.ts +++ b/types/cordova-plugin-qrscanner/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for cordova-plugin-qrscanner v1.0.0 +// Type definitions for cordova-plugin-qrscanner v1.0.1 // Project: https://github.com/bitpay/cordova-plugin-qrscanner // Definitions by: Jason Dreyzehner +// Josh Bronson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -32,7 +33,7 @@ interface QRScanner { * not need to be visible for scanning to function. * @param {function} callback Callback that gets an error or the results string. */ - scan: (callback: (error: QRScannerError, result: String) => any) => void; + scan: (callback: (error: QRScannerError, result: string) => any) => void; /** * Cancels the current scan. If `QRScanner.prepare()` has not been called, @@ -82,7 +83,7 @@ interface QRScanner { * @param {number} index A number representing the index of the camera to use. * @param {function} [callback] Callback that gets an error or the QRScannerStatus object. */ - useCamera: (index: Number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void; + useCamera: (index: number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void; /** * Switch video capture to the device's front camera. If `QRScanner.prepare()` @@ -150,7 +151,7 @@ interface QRScannerStatus { * (`AVAuthorizationStatus.Authorized`). On platforms with permissions granted * at install (Android pre-6.0, Windows Phone) this property is always true. */ - authorized: Boolean, + authorized: boolean, /** * A boolean value which is true if the user permenantly denied camera access @@ -158,59 +159,59 @@ interface QRScannerStatus { * only be gained by requesting the user change their decision (consider * offering a link to the setting via `openSettings()`). */ - denied: Boolean, + denied: boolean, /** * A boolean value which is true if the user is unable to grant permissions due * to parental controls, organization security configuration profiles, or * similar reasons. */ - restricted: Boolean, + restricted: boolean, /** * A boolean value which is true if QRScanner is prepared to capture video and * render it to the view. */ - prepared: Boolean, + prepared: boolean, /** * A boolean value which is true if QRScanner is actively scanning for a QR code. */ - scanning: Boolean, + scanning: boolean, /** * A boolean value which is true if QRScanner is displaying a live preview * from the device's camera. Set to false when the preview is paused. */ - previewing: Boolean, + previewing: boolean, /** * A boolean value which is true when the native webview background is transparent. */ - webviewBackgroundIsTransparent: Boolean, + webviewBackgroundIsTransparent: boolean, /** * A boolean value which is true if the light is enabled. */ - lightEnabled: Boolean, + lightEnabled: boolean, /** * A boolean value which is true only if the users' operating system is able * to `QRScanner.openSettings()`. */ - canOpenSettings: Boolean, + canOpenSettings: boolean, /** * A boolean value which is true only if the users' device can enable a light * in the direction of the currentCamera. */ - canEnableLight: Boolean, + canEnableLight: boolean, /** * A number representing the index of the currentCamera. `0` is the back * camera, `1` is the front. */ - currentCamera: Number + currentCamera: number } /** @@ -218,8 +219,8 @@ interface QRScannerStatus { * * Many QRScanner functions accept a callback with an `error` parameter. When * QRScanner experiences errors, this parameter contains a QRScannerError object -* with properties `name` (_String_), `code` (_Number_), and `_message` -* (_String_). When handling errors, rely only on the `name` or `code` parameter, +* with properties `name` (_string_), `code` (_number_), and `_message` +* (_string_). When handling errors, rely only on the `name` or `code` parameter, *as the specific content of `_message` is not considered part of the plugin's * stable API. * @@ -242,17 +243,17 @@ interface QRScannerError { /** * The standard string identifying the type of this QRScannerError. */ - name: String, + name: string, /** * The standard number identifying the type of this QRScannerError. */ - code: Number, + code: number, /** * A simple message describing this QRScannerError. */ - _message: String + _message: string } declare var QRScanner: QRScanner; diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index d4fa027c93..780890c014 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -14,6 +14,7 @@ interface CronJobStatic { interface CronJob { start(): void; stop(): void; + running: boolean | undefined; } export declare var CronJob: CronJobStatic; diff --git a/types/cropperjs/index.d.ts b/types/cropperjs/index.d.ts index 89d35ed998..a82fa718f9 100644 --- a/types/cropperjs/index.d.ts +++ b/types/cropperjs/index.d.ts @@ -131,6 +131,11 @@ declare namespace cropperjs { */ rotatable?: boolean; /** + * Enable to restore the cropped area after resizing the window. + * @default true + */ + restore?: boolean; + /** * Enable to scale the image. * @default true */ diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 379922d1a7..53ca726230 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -7,7 +7,7 @@ function StepSample() { type HookScenarioResult = cucumber.HookScenarioResult; cucumber.defineSupportCode(function ({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) { - setWorldConstructor(function ({attach, parameters}) { + setWorldConstructor(function ({attach, parameters}: any) { this.attach = attach; this.parameters = parameters; this.visit = function (url: string, callback: Callback) { @@ -19,7 +19,7 @@ function StepSample() { console.log(scenarioResult.status === "failed"); callback(); }); - + Before({ timeout: 1000 }, function (scenarioResult: HookScenarioResult, callback: Callback) { console.log(scenarioResult.status === "failed"); callback(); @@ -35,7 +35,7 @@ function StepSample() { console.log("After"); callback(); }); - + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback?: Callback) => { console.log("After"); callback(); @@ -48,7 +48,7 @@ function StepSample() { Given(/^a variable set to (\d+)$/, (x: string) => { console.log("the number is: " + x); }); - + Given(/^a variable set to (\d+)$/, (x: number) => { console.log(typeof x); }); diff --git a/types/cwise-compiler/cwise-compiler-tests.ts b/types/cwise-compiler/cwise-compiler-tests.ts new file mode 100644 index 0000000000..38e19de886 --- /dev/null +++ b/types/cwise-compiler/cwise-compiler-tests.ts @@ -0,0 +1,76 @@ +/// + +import * as parse from 'cwise-parser'; +import * as ndarray from 'ndarray'; +import * as compile from 'cwise-compiler'; +import * as tape from 'tape'; + +tape("block tests", (t) => { + const ops = require('ndarray-ops'); + const body2 = parse((a: number, b: number[]) => { + a = b[0] + b[1] + 1; + }); + const body23 = parse((a: number, b: number[][]) => { + a = b[0][0] * b[1][0] + b[0][1] * b[1][1] + b[0][2] * b[1][2]; + }); + + // Test with block index at the front of the indices + const c1 = compile({ + args: ["array", { blockIndices: 1 }], + pre: parse(() => { }), + body: body2, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + + const a1 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b1 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [2, 3, 4]); + const ref1 = ndarray([81, 95, 113, 115, 47, 149, 102, 112, 62, 112, 84, 94], [3, 4]); + + c1(a1, b1); + + t.ok(ops.equals(a1, ref1), "front block"); + + // Test with block index at the back of the indices + const c2 = compile({ + args: ["array", { blockIndices: -1 }], + pre: parse(() => { }), + body: body2, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + + const a2 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b2 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [3, 4, 2]); + const ref2 = ndarray([75, 174, 113, 179, 81, 83, 101, 54, 83, 35, 93, 95], [3, 4]); + + c2(a2, b2); + + t.ok(ops.equals(a2, ref2), "back block"); + + // Multiple block indices + const c3 = compile({ + args: ["array", { blockIndices: -2 }], + pre: parse(() => { }), + body: body23, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + const a3 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b3 = ndarray([48, 46, 89, 64, 72, 96, 38, 37, 79, 92, 89, 62, 84, 41, 13, 81, 53, 30, 68, 78, 34, 81, 90, 50, + 82, 97, 46, 18, 11, 79, 15, 68, 88, 58, 71, 84, 76, 35, 74, 82, 27, 47, 59, 25, 78, 61, 10, 43, + 96, 59, 21, 74, 41, 67, 11, 72, 38, 62, 95, 66, 57, 44, 93, 10, 51, 59, 50, 85, 71, 41, 79, 45], [3, 4, 2, 3]); + const ref = ndarray([14928, 11687, 9367, 14228, 6177, 13090, 10655, 7203, 10930, 10030, 8301, 11960], [3, 4]); + + c3(a3, b3); + + t.ok(ops.equals(a3, ref), "block with two indices"); + + t.end(); +}); diff --git a/types/cwise-compiler/index.d.ts b/types/cwise-compiler/index.d.ts new file mode 100644 index 0000000000..e661934a6a --- /dev/null +++ b/types/cwise-compiler/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for cwise-compiler 1.1 +// Project: https://github.com/scijs/cwise-compiler +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { CompiledRoutine } from 'cwise-parser'; +import * as ndarray from 'ndarray'; + +declare namespace cwise_compiler { + interface BlockIndice { + blockIndices: number; + } + interface OffsetArg { + offset: number[]; + array: number; + } + type ArgType = 'array' | 'offset' | 'shape' | 'scalar' | 'index' | BlockIndice | OffsetArg; + interface UserArgs { + args: ArgType[]; + pre: CompiledRoutine; + body: CompiledRoutine; + post: CompiledRoutine; + debug: boolean; + funcName: string; + blockSize: number; + printCode?: boolean; + } + interface Procedure { + argTypes: ArgType[]; + shimArgs: string[]; + arrayArgs: number[]; + arrayBlockIndices: number[]; + scalarArgs: number[]; + offsetArgs: OffsetArg[]; + offsetArgIndex: number[]; + indexArgs: number[]; + shapeArgs: number[]; + funcName: string; + pre: CompiledRoutine; + body: CompiledRoutine; + post: CompiledRoutine; + debug: boolean; + blockSize?: number; + } +} + +declare function cwise_compiler(user_args: cwise_compiler.UserArgs): (a: ndarray, b: ndarray, ...args: ndarray[]) => ndarray; + +export = cwise_compiler; diff --git a/types/cwise-compiler/tsconfig.json b/types/cwise-compiler/tsconfig.json new file mode 100644 index 0000000000..a78923fa03 --- /dev/null +++ b/types/cwise-compiler/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-compiler-tests.ts" + ] +} diff --git a/types/cwise-compiler/tslint.json b/types/cwise-compiler/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise-compiler/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/cwise-parser/cwise-parser-tests.ts b/types/cwise-parser/cwise-parser-tests.ts new file mode 100644 index 0000000000..c50b9be06a --- /dev/null +++ b/types/cwise-parser/cwise-parser-tests.ts @@ -0,0 +1,26 @@ +import * as parser from "cwise-parser"; +// import parser = require("cwise-parser"); +import * as tape from "tape"; + +tape("basic tests", (t) => { + const parsed = parser((a: number, b: number, c: number) => { + a += b; + c = Math.cos(b); + }); + + t.equals(parsed.args.length, 3); + + t.equals(parsed.args[0].lvalue, true); + t.equals(parsed.args[0].rvalue, true); + t.equals(parsed.args[0].count, 1); + + t.equals(parsed.args[1].lvalue, false); + t.equals(parsed.args[1].rvalue, true); + t.equals(parsed.args[1].count, 2); + + t.equals(parsed.args[2].lvalue, true); + t.equals(parsed.args[2].rvalue, false); + t.equals(parsed.args[2].count, 1); + + t.end(); +}); diff --git a/types/cwise-parser/index.d.ts b/types/cwise-parser/index.d.ts new file mode 100644 index 0000000000..d2a06fd7f1 --- /dev/null +++ b/types/cwise-parser/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for cwise-parser 1.0 +// Project: https://github.com/scijs/cwise-parser#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace cwise_parser { + interface CompiledArgument { + name: string; + lvalue: boolean; + rvalue: boolean; + count: number; + } + interface CompiledRoutine { + body: string; + args: CompiledArgument[]; + thisVars: string[]; + localVars: string[]; + } +} + +declare function cwise_parser(func: (a: number, ...args: T[]) => any): cwise_parser.CompiledRoutine; +export = cwise_parser; diff --git a/types/cwise-parser/tsconfig.json b/types/cwise-parser/tsconfig.json new file mode 100644 index 0000000000..ce6c3c1355 --- /dev/null +++ b/types/cwise-parser/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-parser-tests.ts" + ] +} diff --git a/types/cwise-parser/tslint.json b/types/cwise-parser/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise-parser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/cwise/cwise-tests.ts b/types/cwise/cwise-tests.ts new file mode 100644 index 0000000000..66843adfe2 --- /dev/null +++ b/types/cwise/cwise-tests.ts @@ -0,0 +1,366 @@ +import * as cwise from 'cwise'; +import * as ndarray from 'ndarray'; +import * as tape from 'tape'; + +// basic +tape("only allow same shape", (t) => { + const op1 = cwise({ + args: ["array"], + body: (a: number) => { a = 1; } + }); + const op2 = cwise({ + args: ["array", "array"], + body: (a: number, b: number) => { a = b; } + }); + const op3 = cwise({ + args: ["array", "array", "array"], + body: (a: number, b: number, c: number) => { a = b + c; } + }); + const op2block_pos = cwise({ + args: ["array", { blockIndices: 1 }], + body: (a: number, b: number[]) => { a = b[1]; } + }); + const op2block_neg = cwise({ + args: ["array", { blockIndices: -1 }], + body: (a: number, b: number[]) => { a = b[1]; } + }); + + t.doesNotThrow(() => { op1(ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.doesNotThrow(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2block_pos(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.doesNotThrow(() => { op2block_neg(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + + t.throws(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); }); + t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3], [3, 1])); }); + t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); }); + t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2]), ndarray([1, 2, 3], [3])); }); + t.throws(() => { op3(ndarray([1, 2], [2]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.throws(() => { op2block_pos(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.throws(() => { op2block_neg(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.throws(() => { op2block_pos(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + t.throws(() => { op2block_neg(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + + t.end(); +}); + +// binarry +class DumbStorage { + data: Int32Array; + length: number; + constructor(n: number) { + this.data = new Int32Array(n); + this.length = n; + } + get(i: number) { + return this.data[i]; + } + set(i: number, v: number) { + return this.data[i] = v; + } +} + +tape("binary", (t) => { + const binary = cwise({ + args: ["array", "array", "scalar", "shape", "index"], + body(a: number, b: number, t: tape.Test, s: number[], idx: number) { + if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + a = b + 1001; + } + }); + + function testBinary1D(P: ndarray, Q: ndarray, testName: string) { + t.equals(P.shape[0], Q.shape[0], testName + "; shape"); + for (let i = 0; i < P.shape[0]; ++i) { + Q.set(i, i); + P.set(i, 0); + } + binary(P, Q, t); + for (let i = 0; i < P.shape[0]; ++i) { + if (!(P.get(i) === i + 1001)) { + t.fail(testName + "; encountered " + P.get(i) + " instead of " + (i + 1001) + " at " + i); + return; + } + } + t.pass(testName); + } + + const A1 = ndarray(new Int32Array(128)); + const B1 = ndarray(new Int32Array(128)); + + testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(0)), "length==0"); + testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(1)), "length==1"); + testBinary1D(A1, B1, "A, B"); + testBinary1D(A1.lo(32), B1.hi(128 - 32), "A.lo(32), B.hi(128-32)"); + testBinary1D(A1.step(-1), B1, "A.step(-1), B"); + testBinary1D(A1, B1.step(-1), "A, B.step(-1)"); + + const A2 = ndarray(new DumbStorage(128) as any); + const B2 = ndarray(new DumbStorage(128) as any); + testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(0) as any), "DS; length==0"); + testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(1) as any), "DS; length==0"); + testBinary1D(A2, B2, "DS; A, B"); + testBinary1D(A2.lo(32), B2.hi(128 - 32), "DS; A.lo(32), B.hi(128-32)"); + testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B"); + testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)"); + + const X = ndarray(new Int32Array(64 * 64), [64, 64]); + const Y = ndarray(new Int32Array(64 * 64), [64, 64]); + + function testBinary2D(P: ndarray, Q: ndarray, testName: string) { + for (let i = 0; i < X.shape[0]; ++i) { + for (let j = 0; j < X.shape[1]; ++j) { + X.set(i, j, -10000); + Y.set(i, j, -256); + } + } + t.equals(P.shape[0], Q.shape[0], testName + "; shape[0]"); + t.equals(P.shape[1], Q.shape[1], testName + "; shape[1]"); + for (let i = 0; i < P.shape[0]; ++i) { + for (let j = 0; j < P.shape[1]; ++j) { + Q.set(i, j, i * 1000 + j); + P.set(i, j, 0); + } + } + binary(P, Q, t, P.shape); + for (let i = 0; i < P.shape[0]; ++i) { + for (let j = 0; j < P.shape[1]; ++j) { + if (!(P.get(i, j) === i * 1000 + j + 1001)) { + t.fail(testName + "; encountered " + P.get(i, j) + " instead of " + (i * 1000 + j + 1001) + " at (" + i + "," + j + ")"); + return; + } + } + } + t.pass(testName); + } + + testBinary2D(X, Y, "X, Y"); + testBinary2D(X.transpose(1, 0), Y.transpose(1, 0), "X.T, Y.T"); + testBinary2D(X.transpose(1, 0), Y, "X.T, Y"); + testBinary2D(X, Y.transpose(1, 0), "X, Y.T"); + testBinary2D(X.hi(32, 32), Y.hi(32, 32), "X.hi(32,32), Y.hi(32,32)"); + testBinary2D(X.hi(31, 31), Y.hi(31, 31), "X.hi(31,31), Y.hi(31,31)"); + testBinary2D(X.hi(0, 32), Y.hi(0, 32), "X.hi(0,32), Y.hi(0,32)"); + testBinary2D(X.transpose(1, 0).hi(0, 32), Y.hi(0, 32), "X.T.hi(0,32), Y.hi(0,32)"); + testBinary2D(X.transpose(1, 0).hi(33, 33), Y.hi(33, 33), "X.T.hi(33,33), Y.hi(33,33)"); + testBinary2D(X.transpose(1, 0).hi(31, 31), Y.hi(31, 31), "X.T.hi(31,31), Y.hi(31,31)"); + + t.end(); +}); + +// browserify +import * as browserify from "browserify"; +import * as vm from 'vm'; +import * as path from 'path'; + +const cases = ["unary", "binary", "offset", "fill"]; + +bundleCasesFrom(0); + +function bundleCasesFrom(i: number) { + if (i >= cases.length) return; + const b = browserify(); + b.ignore("tape"); + b.add(__dirname + "/" + cases[i] + ".js"); + b.transform(path.normalize(__dirname + "/../cwise.js")); + tape(cases[i], (t) => { // Without nested tests, the asynchronous nature of bundle causes issues with tape... + b.bundle((err, src) => { + if (err) { + throw new Error("failed to bundle!"); + } + vm.runInNewContext(src.toString(), { + test: t.test.bind(t), + Buffer, + Int8Array, + Int16Array, + Int32Array, + Float32Array, + Float64Array, + Uint8Array, + Uint16Array, + Uint32Array, + Uint8ClampedArray, + console: { log: console.log.bind(console) } + }); + t.end(); + }); + }); + bundleCasesFrom(i + 1); +} + +// fill +tape("fill", (t) => { + const fill = cwise({ + args: ["index", "array", "scalar"], + body(idx, out, f) { + out = f.apply(undefined, idx); + } + }); + + const xlen = 10; + const ylen = 5; + const array = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]); + + fill(array, (row: number, col: number) => { + return 0; + }); + + for (let i = 0; i < xlen; i++) { + for (let j = 0; j < ylen; j++) { + t.equals(array.get(i, j), 0, 'fill (' + i + ',' + j + ')'); + } + } + + fill(array, (row: number, col: number) => { + return 10 * (row + col); + }); + + for (let i = 0; i < xlen; i++) { + for (let j = 0; j < ylen; j++) { + t.equals(array.get(i, j), 10 * (i + j), 'fill (' + i + ',' + j + ')'); + } + } + + t.end(); +}); + +// offset +tape("offset", (t) => { + const binary = cwise({ + args: ["array", "array", { offset: [1], array: 1 }, "scalar", "shape", "index"], + body(a, b, c, t, s, idx) { + if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + a = c + b + 1000; + } + }); + + function testBinary1D(P: ndarray, Q: ndarray, testName: string) { + t.equals(P.shape[0], Q.shape[0] - 1, testName + "; shape"); + for (let i = 0; i < P.shape[0]; ++i) { + Q.set(i, i); + P.set(i, 0); + } + Q.set(P.shape[0], P.shape[0]); + binary(P, Q.hi(Q.shape[0] - 1), t); + for (let i = 0; i < P.shape[0]; ++i) { + if (!(P.get(i) === 2 * i + 1001)) { + t.fail(testName + "; encountered " + P.get(i) + " instead of " + (2 * i + 1001) + " at " + i); + return; + } + } + t.pass(testName); + } + + const A1 = ndarray(new Int32Array(128)); + const B1 = ndarray(new Int32Array(129)); + + testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(1)), "length==0"); + testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(2)), "length==1"); + testBinary1D(A1, B1, "A, B"); + testBinary1D(A1.lo(32), B1.lo(32), "A.lo(32), B.lo(32)"); + testBinary1D(A1.step(-1), B1, "A.step(-1), B"); + testBinary1D(A1, B1.step(-1), "A, B.step(-1)"); + + const A2 = ndarray(new DumbStorage(128) as any); + const B2 = ndarray(new DumbStorage(129) as any); + testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(1) as any), "DS; length==0"); + testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(2) as any), "DS; length==1"); + testBinary1D(A2, B2, "DS; A, B"); + testBinary1D(A2.lo(32), B2.lo(32), "DS; A.lo(32), B.lo(32)"); + testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B"); + testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)"); + + t.end(); +}); + +// unary + +tape("unary", (t) => { + const unary = cwise({ + args: ["array"], + body(a) { + ++a; + } + }); + + function testUnary1D(arr: ndarray, testName: string) { + for (let i = 0; i < arr.shape[0]; ++i) { + arr.set(i, i); + } + unary(arr); + for (let i = 0; i < arr.shape[0]; ++i) { + if (!(arr.get(i) === i + 1)) { + t.fail(testName + "; encountered " + arr.get(i) + " instead of " + (i + 1) + " at " + i); + return; + } + } + t.pass(testName); + } + const simple_zeros = ndarray(new Int32Array(4096)); + + testUnary1D(simple_zeros.hi(0), "simple_zeros.hi(0)"); + testUnary1D(simple_zeros.hi(1), "simple_zeros.hi(1)"); + testUnary1D(simple_zeros.hi(2), "simple_zeros.hi(2)"); + testUnary1D(simple_zeros, "simple_zeros"); + testUnary1D(simple_zeros.hi(31), "simple_zeros.hi(31)"); + testUnary1D(simple_zeros.hi(32), "simple_zeros.hi(32)"); + testUnary1D(simple_zeros.hi(33), "simple_zeros.hi(33)"); + testUnary1D(simple_zeros.step(-1), "simple_zeros.step(-1)"); + testUnary1D(simple_zeros.step(3), "simple_zeros.step(3)"); + testUnary1D(simple_zeros.step(4), "simple_zeros.step(4)"); + testUnary1D(simple_zeros.step(5).lo(10), "simple_zeros.step(5).lo(10)"); + + const custom_zeros = ndarray(new DumbStorage(4096) as any); + + testUnary1D(custom_zeros.hi(0), "custom_zeros.hi(0)"); + testUnary1D(custom_zeros.hi(1), "custom_zeros.hi(1)"); + testUnary1D(custom_zeros.hi(2), "custom_zeros.hi(2)"); + testUnary1D(custom_zeros, "custom_zeros"); + testUnary1D(custom_zeros.hi(31), "custom_zeros.hi(31)"); + testUnary1D(custom_zeros.hi(32), "custom_zeros.hi(32)"); + testUnary1D(custom_zeros.hi(33), "custom_zeros.hi(33)"); + testUnary1D(custom_zeros.step(-1), "custom_zeros.step(-1)"); + testUnary1D(custom_zeros.step(3), "custom_zeros.step(3)"); + testUnary1D(custom_zeros.step(4), "custom_zeros.step(4)"); + testUnary1D(custom_zeros.step(5).lo(10), "custom_zeros.step(5).lo(10)"); + + function testUnary2D(arr: ndarray, testName: string) { + for (let i = 0; i < arr.shape[0]; ++i) { + for (let j = 0; j < arr.shape[1]; ++j) { + arr.set(i, j, i + j * arr.shape[0]); + } + } + unary(arr); + for (let i = 0; i < arr.shape[0]; ++i) { + for (let j = 0; j < arr.shape[1]; ++j) { + if (!(arr.get(i, j) === 1 + i + j * arr.shape[0])) { + t.fail(testName + "; encountered " + arr.get(i, j) + " instead of " + (1 + i + j * arr.shape[0]) + " at (" + i + "," + j + ")"); + return; + } + } + } + t.pass(testName); + } + + const M1 = ndarray(new Int32Array(128 * 128), [128, 128]); + testUnary2D(M1, "M"); + testUnary2D(M1.hi(10, 10), "M.hi(10, 10)"); + testUnary2D(M1.lo(100, 1), "M.lo(100,1)"); + testUnary2D(M1.transpose(1, 0), "M.transpose(1,0)"); + testUnary2D(M1.step(-1, 1), "M.step(-1, 1)"); + testUnary2D(M1.step(-5, -2), "M.step(-5, -2)"); + testUnary2D(M1.step(16, 3), "M.step(16, 3)"); + + const M2 = ndarray(new DumbStorage(128 * 128) as any, [128, 128]); + testUnary2D(M2, "DS; M"); + testUnary2D(M2.hi(10, 10), "DS; M.hi(10, 10)"); + testUnary2D(M2.lo(100, 1), "DS; M.lo(100,1)"); + testUnary2D(M2.transpose(1, 0), "DS; M.transpose(1,0)"); + testUnary2D(M2.step(-1, 1), "DS; M.step(-1, 1)"); + testUnary2D(M2.step(-5, -2), "DS; M.step(-5, -2)"); + testUnary2D(M2.step(16, 3), "DS; M.step(16, 3)"); + + t.end(); +}); diff --git a/types/cwise/index.d.ts b/types/cwise/index.d.ts new file mode 100644 index 0000000000..d99d43ce59 --- /dev/null +++ b/types/cwise/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for cwise 1.0 +// Project: https://github.com/scijs/cwise#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { ArgType } from "cwise-compiler"; +import * as ndarray from "ndarray"; + +declare function cwise(a: string | cwise.UserArgs): cwise.Return; + +declare namespace cwise { + type Arg = ndarray | ((row: number, col: number) => number) | number[] | any; + type Return = (a: ndarray, ...b: Arg[]) => void; + interface UserArgs { + args: ArgType[]; + pre?(a: number, ...args: any[]): void; + body(a: number, ...args: any[]): void; + post?(a: number, ...args: any[]): void; + funcName?: string; + blockSize?: number; + printCode?: boolean; + } +} +export = cwise; diff --git a/types/cwise/tsconfig.json b/types/cwise/tsconfig.json new file mode 100644 index 0000000000..f4aaf9b1a3 --- /dev/null +++ b/types/cwise/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cwise/tslint.json b/types/cwise/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index bb713192e8..b95da5774f 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -389,9 +389,13 @@ mergedArray = d3Array.shuffle(mergedArray, 1, 3); numbersArray = d3Array.ticks(1, 10, 5); +// tickIncrement() ------------------------------------------------------------------ + +let numDiff: number = d3Array.tickIncrement(1, 10, 5); + // tickStep() ------------------------------------------------------------------ -numbersArray = d3Array.tickStep(1, 10, 5); +numDiff = d3Array.tickStep(1, 10, 5); // transpose() ----------------------------------------------------------------- diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 74ecbb0e36..aee2ef38c7 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-array module 1.1 +// Type definitions for D3JS d3-array module 1.2 // Project: https://github.com/d3/d3-array // Definitions by: Alex Ford , Boris Yankov , Tom Wanzek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.2.0 // -------------------------------------------------------------------------- // Shared Types and Interfaces @@ -246,14 +246,45 @@ export function shuffle(array: T[], lo?: number, hi?: number): T[]; /** * Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). + * Each value is a power of ten multiplied by 1, 2 or 5. See also d3.tickIncrement, d3.tickStep and linear.ticks. + * + * Ticks are inclusive in the sense that they may include the specified start and stop values if (and only if) they are exact, + * nicely-rounded values consistent with the inferred step. More formally, each returned tick t satisfies start ≤ t and t ≤ stop. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. */ export function ticks(start: number, stop: number, count: number): number[]; /** - * Generate an array of with the differences between adjecent ticks, had the same arguments - * been passed to ticks(start, stop, count) + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Like d3.tickStep, except requires that start is always less than or equal to step, and if the tick step for the given start, + * stop and count would be less than one, returns the negative inverse tick step instead. + * + * This method is always guaranteed to return an integer, and is used by d3.ticks to avoid guarantee that the returned tick values + * are represented as precisely as possible in IEEE 754 floating point. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. */ -export function tickStep(start: number, stop: number, count: number): number[]; +export function tickIncrement(start: number, stop: number, count: number): number; + +/** + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Note that due to the limited precision of IEEE 754 floating point, the returned value may not be exact decimals; + * use d3-format to format numbers for human consumption. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function tickStep(start: number, stop: number, count: number): number; /** * Transpose a matrix provided in Array of Arrays format. @@ -298,6 +329,9 @@ export interface HistogramGenerator { * Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold * setting approach only works, when the materialized values are numbers! * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * * @param count The desired number of uniform bins. */ thresholds(count: number): this; @@ -306,6 +340,9 @@ export interface HistogramGenerator { * Divides the domain uniformly into approximately count bins. IMPORTANT: This threshold * setting approach only works, when the materialized values are numbers! * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * * @param count A function which accepts as arguments the array of materialized values, and * optionally the domain minimum and maximum. The function calcutates and returns the suggested * number of bins. @@ -313,6 +350,10 @@ export interface HistogramGenerator { thresholds(count: ThresholdCountGenerator): this; /** * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * * @param thresholds Array of threshold values used for binning. The elements must * be of the same type as the materialized values of the histogram. */ @@ -321,6 +362,9 @@ export interface HistogramGenerator { * Set a threshold accessor function, which returns the array of values to be used as * thresholds in determining the bins. * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * * @param thresholds A function which accepts as arguments the array of materialized values, and * optionally the domain minimum and maximum. The function calcutates and returns the array of values to be used as * thresholds in determining the bins. diff --git a/types/d3-contour/d3-contour-tests.ts b/types/d3-contour/d3-contour-tests.ts new file mode 100644 index 0000000000..751dfe99c9 --- /dev/null +++ b/types/d3-contour/d3-contour-tests.ts @@ -0,0 +1,189 @@ +/** + * Typescript definition tests for d3/d3-contour module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Contour from 'd3-contour'; +import { + range, + thresholdSturges, + ThresholdArrayGenerator, + ThresholdCountGenerator +} from 'd3-array'; +import { geoPath } from 'd3-geo'; +import { randomNormal } from 'd3-random'; + +// ----------------------------------------------------------------------------- +// Preparatory Steps +// ----------------------------------------------------------------------------- + +// Some test setup is based on Contour Plot II Golstein-Price function at https://bl.ocks.org/mbostock/f48ff9c1af4d637c9a518727f5fdfef5 + +const n = 256; +const m = 256; +const values: number[] = new Array(n * m); +for (let j = 0.5, k = 0; j < m; ++j) { + for (let i = 0.5; i < n; ++i, ++k) { + values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3); + } +} + +function goldsteinPrice(x: number, y: number) { + return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y)) + * (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y)); +} + +let size: [number, number]; +let boolFlag: boolean; +const thresholdArrayGen: ThresholdArrayGenerator = (values: number[], min: number, max: number) => { + let thresholds: number[]; + thresholds = [values[1], values[2], values[4]]; + return thresholds; +}; + +let thresholdGenerator: ThresholdArrayGenerator | ThresholdCountGenerator; +let pathStringMaybe: string | null; +let num: number; + +const pathSolo = geoPath(); + +// ----------------------------------------------------------------------------- +// Test Contour Generator +// ----------------------------------------------------------------------------- + +// Get contour generator ------------------------------------------------------- + +let contGen: d3Contour.Contours = d3Contour.contours(); + +// Configure contour generator ================================================= + +// size(...) ------------------------------------------------------------------- + +// set with chainability +contGen = contGen.size([n, m]); + +size = contGen.size(); + +// smooth(...) ----------------------------------------------------------------- + +// set with chainability +contGen = contGen.smooth(true); + +boolFlag = contGen.smooth(); + +// thresholds(...) ------------------------------------------------------------- + +// set with count +contGen = contGen.thresholds(10); + +// set with array +const thresholds1 = range(1, 21) + .map(p => Math.pow(2, p)); +contGen = contGen.thresholds(thresholds1); + +// set with threshold array generator + +contGen = contGen.thresholds(thresholdArrayGen); // mock + +// set with threshold count generator + +contGen = contGen.thresholds(thresholdSturges); + +// get +thresholdGenerator = contGen.thresholds(); + +// Use contour generator ======================================================= + +pathStringMaybe = pathSolo(contGen(values)[0]); + +// ----------------------------------------------------------------------------- +// Test Contour Generator for Density Estimates +// ----------------------------------------------------------------------------- + +interface CustomDatum { + x: number; + y: number; +} + +// Get contour generator ------------------------------------------------------- + +let contDensDefault: d3Contour.ContourDensity<[number, number]> = d3Contour.contourDensity(); +let contDensCustom: d3Contour.ContourDensity = d3Contour.contourDensity(); + +// Configure contour generator ================================================= + +// x(...) ---------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.x((datum) => { + const d: CustomDatum = datum; // check passed in argument type + return d.x; +}); + +// get +const xAcc: (d: CustomDatum) => number = contDensCustom.x(); + +// y(...) ---------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.y((datum) => { + const d: CustomDatum = datum; // check passed in argument type + return d.y; +}); + +// get +const yAcc: (d: CustomDatum) => number = contDensCustom.y(); + +// size(...) ------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.size([900, 600]); + +size = contDensCustom.size(); + +// cellSize(...) ----------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.cellSize(3); + +num = contDensCustom.cellSize(); + +// thresholds(...) ------------------------------------------------------------- + +// set with count +contDensCustom = contDensCustom.thresholds(10); + +// set with array +contDensCustom = contDensCustom.thresholds([0.1, 0.25, 0.5, 0.75, 1]); + +// set with threshold array generator +contDensCustom = contDensCustom.thresholds(thresholdArrayGen); // mock + +// set with threshold count generator +contDensCustom = contDensCustom.thresholds(thresholdSturges); + +// get +thresholdGenerator = contDensCustom.thresholds(); + +// bandwidth(...) -------------------------------------------------------------- +// set with chainability +contDensCustom = contDensCustom.bandwidth(40); +// get +num = contDensCustom.bandwidth(); + +// Use contour generator ======================================================= + +const indNorm: CustomDatum[] = []; +const rX = randomNormal(); +const rY = randomNormal(1, 2); +for (let i = 0; i < 1000; i++) { + indNorm.push({ + x: rX(), + y: rY() + }); +} + +pathStringMaybe = pathSolo(contDensCustom(indNorm)[0]); diff --git a/types/d3-contour/index.d.ts b/types/d3-contour/index.d.ts new file mode 100644 index 0000000000..789ff32a5f --- /dev/null +++ b/types/d3-contour/index.d.ts @@ -0,0 +1,246 @@ +// Type definitions for d3-contour 1.1 +// Project: https://d3js.org/d3-contour/ +// Definitions by: Tom Wanzek , Hugues Stefanski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Last module patch version validated against: 1.1.0 + +import { MultiPolygon } from 'geojson'; +import { ThresholdArrayGenerator, ThresholdCountGenerator } from 'd3-array'; + +/** + * An extended GeoJSON MultiPolygon representing a contour. + */ +export interface ContourMultiPolygon extends MultiPolygon { + /** + * Threshold value of the contour. + */ + value: number; +} + +/** + * A contour generator which computes contour polygons by applying marching squares to a rectangular array of numeric values. + * + * For each threshold value, the contour generator constructs a GeoJSON MultiPolygon geometry object representing the area + * where the input values are greater than or equal to the threshold value. + * The geometry is in planar coordinates, where ⟨i + 0.5, j + 0.5⟩ corresponds to element i + jn in the input values array. + * + */ +export interface Contours { + /** + * Computes the contours for the given array of values, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the input values are greater than or equal to the corresponding threshold value; + * the threshold value for each geometry object is exposed as geometry.value. + * + * The returned geometry objects are typically passed to d3.geoPath to display, + * using null or d3.geoIdentity as the associated projection + * + * @param values Array of input values. The input values must be an array of length n×m where [n, m] is the contour generator’s size; + * furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. + */ + (values: number[]): ContourMultiPolygon[]; + + /** + * Return the expected size of the input values grid, which defaults to [1,1]. + */ + size(): [number, number]; + /** + * Sets the expected size of the input values grid to the contour generator and returns the contour generator. + * + * @param size Size of the input values grid specified as an array [n, m] + * where n is the number of columns in the grid and m is the number of rows; n and m must be positive integers. + */ + size(size: [number, number]): this; + + /** + * Returns the current smoothing flag, which defaults to true. + */ + smooth(): boolean; + /** + * Sets whether or not the generated contour polygons are smoothed using linear interpolation and returns the contour generator. + * + * @param smooth Flag to enable linear interpolation. The default is "true". + */ + smooth(smooth: boolean): this; + + /** + * Returns the current threshold generator, which by default implements Sturges’ formula. + */ + thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; + /** + * Sets the threshold generator to use the specified count and returns this contour generator. + * The input values’ extent will be uniformly divided into approximately count bins. + * + * @param count Expected number of threshold bins. + */ + thresholds(count: number): this; + /** + * Sets the threshold generator to the specified array and returns this contour generator. + * + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated contour corresponds to the area where the input values are greater than or equal to x0; + * the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. + * + * @param thresholds Array of thresholds to use. + */ + thresholds(thresholds: number[]): this; + /** + * Sets the threshold generator to the specified function and returns this contour generator. + * + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated contour corresponds to the area where the input values are greater than or equal to x0; + * the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. + * + * @param thresholds A threshold generator function. The threshold generator function is passed the array of input values + * as its argument and returns either an array of calculated thresholds, or the count of thresholds to use. + */ + thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator): this; +} + +/** + * Construct a new contour generator with the default settings. + */ +export function contours(): Contours; + +/** + * A contour generator for density estimates. + */ +export interface ContourDensity { + /** + * Estimates the density contours for the given array of data, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the estimated number of points per square pixel is greater than or equal to + * the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value. + * The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection. + * See also d3.contours. + * + * The x- and y-coordinate for each data point are computed using density.x and density.y. + * The generated contours are only accurate within the estimator’s defined size. + * + * @param data Array of input data. + */ + (data: Datum[]): ContourMultiPolygon[]; + + /** + * Returns the current x-coordinate accessor. + * The default x-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 0. + */ + x(): (d: Datum) => number; + /** + * Sets the x-coordinate accessor and returns the density contour estimator. + * + * @param x An x-coordinate accessor function, which accepts as input an element of the input data array and returns the + * x-coordinate. + */ + x(x: (d: Datum) => number): this; + + /** + * Returns the current y-coordinate accessor. + * The default y-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 1. + */ + y(): (d: Datum) => number; + /** + * Sets the y-coordinate accessor and returns the density contour estimator. + * + * @param y An y-coordinate accessor function, which accepts as input an element of the input data array and returns the + * y-coordinate. + */ + y(y: (d: Datum) => number): this; + + /** + * Returns the current size, which defaults to [960, 500]. + */ + size(): [number, number]; + /** + * Sets the size of the density estimator to the specified bounds and returns the density contour estimator. + * + * @param size The size is specified as an array [width, height], where width is the maximum x-value and height is the maximum y-value. + */ + size(size: [number, number]): this; + + /** + * Returns the current cell size, which defaults to 4. + */ + cellSize(): number; + /** + * Sets the size of individual cells in the underlying bin grid to the specified positive integer and returns the density contour estimator. + * + * The cell size is rounded down to the nearest power of two. Smaller cells produce more detailed contour polygons, but are more expensive to compute. + * + * @param cellSize Cell size, a positive integer. + */ + cellSize(cellSize: number): this; + + /** + * Returns the current threshold generator, which by default generates about twenty nicely-rounded density thresholds. + */ + thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; + /** + * Sets the threshold generator to use the specified count and returns this density contour estimator. + * Approximately count uniformly-spaced nicely-rounded thresholds will be generated. + * + * @param count Expected number of thresholds. + */ + thresholds(count: number): this; + /** + * Sets the threshold generator to the specified array and returns this density contour estimator. + * + * Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area + * where the estimated density is greater than or equal to x0; the second contour corresponds to the area + * where the estimated density is greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero. + * + * @param thresholds Array of thresholds to use. + */ + thresholds(thresholds: number[]): this; + /** + * Sets the threshold generator to the specified function and returns this density contour estimator. + * + * Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area + * where the estimated density is greater than or equal to x0; the second contour corresponds to the area + * where the estimated density is greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero. + * + * @param thresholds A threshold generator function. The threshold generator function is passed the array of input values + * as its argument and returns either an array of calculated thresholds, or the count of thresholds to use. + */ + thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator): this; + + /** + * Returns the current bandwidth, which defaults to 20.4939…. + */ + bandwidth(): number; + /** + * Sets the bandwidth (the standard deviation) of the Gaussian kernel and returns the density contour estimator. + * + * @param bandwidth Bandwidth (the standard deviation) of the Gaussian kernel. + * The specified bandwidth is currently rounded to the nearest supported value by this implementation, and must be nonnegative. + */ + bandwidth(bandwidth: number): this; +} + +/** + * Construct a new contour generator for density estimates with the default settings. + * + * The default settings assume that, the elements of the data array used + * with the density contour generator are two-element arrays. The first element + * corresponds to the x-dimension, the second to the y-dimension. + */ +export function contourDensity(): ContourDensity<[number, number]>; +/** + * Construct a new contour generator for density estimates. + * + * The generic refers to the data type of an element in the data array + * used with the density contour generator. + * + * Important: ensure that the x- and y-accessor functions are configured to + * match the data type used for the generic Datum. + */ +export function contourDensity(): ContourDensity; diff --git a/types/d3-contour/tsconfig.json b/types/d3-contour/tsconfig.json new file mode 100644 index 0000000000..4f9d0a8284 --- /dev/null +++ b/types/d3-contour/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-contour-tests.ts" + ] +} diff --git a/types/d3-contour/tslint.json b/types/d3-contour/tslint.json new file mode 100644 index 0000000000..08016de61a --- /dev/null +++ b/types/d3-contour/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/d3-drag/d3-drag-tests.ts b/types/d3-drag/d3-drag-tests.ts index 4283cb259f..581b757717 100644 --- a/types/d3-drag/d3-drag-tests.ts +++ b/types/d3-drag/d3-drag-tests.ts @@ -88,6 +88,12 @@ circleDrag = circleDrag containerAccessor = circleDrag.container(); +// clickDistance(...) --------------------------------------------------------- + +circleDrag = circleDrag.clickDistance(5); + +const distance: number = circleDrag.clickDistance(); + // set and get filter --------------------------------------------------------- let filterFn: (this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | NodeListOf) => boolean; diff --git a/types/d3-drag/index.d.ts b/types/d3-drag/index.d.ts index d3a65fb377..7105bd4e4d 100644 --- a/types/d3-drag/index.d.ts +++ b/types/d3-drag/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-drag module 1.0 +// Type definitions for D3JS d3-drag module 1.1 // Project: https://github.com/d3/d3-drag/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.2 +// Last module patch version validated against: 1.1.0 import { ArrayLike, Selection, ValueFn } from 'd3-selection'; @@ -164,6 +164,20 @@ export interface DragBehavior): this; + /** + * Return the current click distance threshold, which defaults to zero. + */ + clickDistance(): number; + /** + * Set the maximum distance that the mouse can move between mousedown and mouseup that will trigger + * a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to + * distance from its position on mousedown, the click event follwing mouseup will be suppressed. + * + * @param distance The distance threshold between mousedown and mouseup measured in client coordinates (event.clientX and event.clientY). + * The default is zero. + */ + clickDistance(distance: number): this; + /** * Return the first currently-assigned listener matching the specified typenames, if any. * diff --git a/types/d3-ease/index.d.ts b/types/d3-ease/index.d.ts index 3de6fd2e87..1f2b5f4cdd 100644 --- a/types/d3-ease/index.d.ts +++ b/types/d3-ease/index.d.ts @@ -87,7 +87,7 @@ export interface PolynomialEasingFactory { * * @param e Exponent for polynomial easing. */ - exponent(e: number): PolynomialEasingFactory; + exponent(e: number): PolynomialEasingFactory; } /** @@ -240,7 +240,7 @@ export interface BackEasingFactory { * * @param s Overshoot parameter */ - overshoot(s: number): BackEasingFactory; + overshoot(s: number): BackEasingFactory; } /** @@ -282,14 +282,14 @@ export interface ElasticEasingFactory { * * @param a Amplitude for elastic easing. */ - amplitude(a: number): ElasticEasingFactory; - /** - * Returns a new elastic easing with the specified amplitude a. - * Defaults to 0.3,if not specified. - * - * @param p Period for elastic easing. - */ - period(p: number): ElasticEasingFactory; + amplitude(a: number): ElasticEasingFactory; + /** + * Returns a new elastic easing with the specified amplitude a. + * Defaults to 0.3,if not specified. + * + * @param p Period for elastic easing. + */ + period(p: number): ElasticEasingFactory; } /** diff --git a/types/d3-format/d3-format-tests.ts b/types/d3-format/d3-format-tests.ts index 57a98e26c6..9c11d07c70 100644 --- a/types/d3-format/d3-format-tests.ts +++ b/types/d3-format/d3-format-tests.ts @@ -48,7 +48,6 @@ let type: 'e' | 'f' | 'g' | 'r' | 's' | '%' | 'p' | 'b' | 'o' | 'd' | 'x' | 'X' let formatString: string = specifier.toString(); - // ---------------------------------------------------------------------- // Test Precision Suggestors // ---------------------------------------------------------------------- @@ -76,13 +75,22 @@ localeDef = { grouping: [3], currency: ["", ""], numerals : ["\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669"] -} +}; + +localeDef = { + decimal: "\u066b", + thousands: "\u066c", + grouping: [3], + currency: ["", ""], + percent : "\u202f%" +}; let decimal: string = localeDef.decimal; let thousands: string = localeDef.thousands; -let grouping: Array = localeDef.grouping; +let grouping: number[] = localeDef.grouping; let currency: [string, string] = localeDef.currency; let numerals: string[] | undefined = localeDef.numerals; +let percent: string | undefined = localeDef.percent; localeObj = d3Format.formatLocale(localeDef); diff --git a/types/d3-format/index.d.ts b/types/d3-format/index.d.ts index be6c2b9a99..34cf80c047 100644 --- a/types/d3-format/index.d.ts +++ b/types/d3-format/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-format module 1.1 +// Type definitions for D3JS d3-format module 1.2 // Project: https://github.com/d3/d3-format/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.2.0 /** * Specification of locale to use when creating a new FormatLocaleObject @@ -27,16 +27,19 @@ export interface FormatLocaleDefinition { */ currency: [string, string]; /** - * An array of ten strings to replace the numerals 0-9. + * An optional array of ten strings to replace the numerals 0-9. */ numerals?: string[]; + /** + * An optional symbol to replace the `percent` suffix; the percent suffix (defaults to "%") + */ + percent?: string; } /** * A Format Locale Object */ export interface FormatLocaleObject { - /** * Returns a new format function for the given string specifier. The returned function * takes a number as the only argument, and returns a string representing the formatted number. @@ -219,7 +222,6 @@ export function precisionFixed(step: number): number; */ export function precisionPrefix(step: number, value: number): number; - /** * Returns a suggested decimal precision for format types that round to significant digits * given the specified numeric step and max values. diff --git a/types/d3-format/tslint.json b/types/d3-format/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/d3-format/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index f6e4fa150d..bff408ce6b 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -3,10 +3,10 @@ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - // Last module patch version validated against: 1.6.1 +import * as GeoJSON from 'geojson'; + // ---------------------------------------------------------------------- // Shared Interfaces and Types // ---------------------------------------------------------------------- @@ -926,7 +926,8 @@ export interface GeoPath { * * Any additional arguments are passed along to the pointRadius accessor. * - * If the rendering context is null, the function returns an SVG Path string, otherwise the function renders to the current context. + * IMPORTANT: If the rendering context of the geoPath generator is null, + * then the geoPath is returned as an SVG path data string. * * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover). * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. @@ -935,7 +936,36 @@ export interface GeoPath { * * @param object An object to be rendered. */ - (this: This, object: DatumObject, ...args: any[]): string | undefined; + (this: This, object: DatumObject, ...args: any[]): string | null; + /** + * Renders the given object, which may be any GeoJSON feature or geometry object: + * + * + Point - a single position. + * + MultiPoint - an array of positions. + * + LineString - an array of positions forming a continuous line. + * + MultiLineString - an array of arrays of positions forming several lines. + * + Polygon - an array of arrays of positions forming a polygon (possibly with holes). + * + MultiPolygon - a multidimensional array of positions forming multiple polygons. + * + GeometryCollection - an array of geometry objects. + * + Feature - a feature containing one of the above geometry objects. + * + FeatureCollection - an array of feature objects. + * + * The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates. + * + * + * Any additional arguments are passed along to the pointRadius accessor. + * + * IMPORTANT: If the geoPath generator has been configured with a rendering context, + * then the geoPath is rendered to this context as a sequence of path method calls and this function returns void. + * + * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover). + * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. + * + * The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation. + * + * @param object An object to be rendered. + */ + (this: This, object: DatumObject, ...args: any[]): void; /** * Returns the projected planar area (typically in square pixels) for the specified GeoJSON object. diff --git a/types/d3-random/d3-random-tests.ts b/types/d3-random/d3-random-tests.ts index 8cd72d9f0e..7385d3e984 100644 --- a/types/d3-random/d3-random-tests.ts +++ b/types/d3-random/d3-random-tests.ts @@ -7,7 +7,7 @@ */ import * as d3Random from 'd3-random'; - +import * as seedrandom from 'seedrandom'; // ------------------------------------------------------------ // Preparatory Steps @@ -19,40 +19,70 @@ let randomNumberGenerator: () => number; // randomUniform // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomUniform(); -randomNumberGenerator = d3Random.randomUniform(0.2); -randomNumberGenerator = d3Random.randomUniform(0.2, 5); +let prngUniform: d3Random.RandomUniform; + +prngUniform = d3Random.randomUniform; +prngUniform = d3Random.randomUniform.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngUniform(); +randomNumberGenerator = prngUniform(0.2); +randomNumberGenerator = prngUniform(0.2, 5); // ------------------------------------------------------------ // randomNormal // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomNormal(); -randomNumberGenerator = d3Random.randomNormal(3); -randomNumberGenerator = d3Random.randomNormal(3, 4); +let prngNormal: d3Random.RandomNormal; + +prngNormal = d3Random.randomNormal; +prngNormal = d3Random.randomNormal.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngNormal(); +randomNumberGenerator = prngNormal(3); +randomNumberGenerator = prngNormal(3, 4); // ------------------------------------------------------------ // randomLogNormal // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomLogNormal(); -randomNumberGenerator = d3Random.randomLogNormal(3); -randomNumberGenerator = d3Random.randomLogNormal(3, 4); +let prngLogNormal: d3Random.RandomLogNormal; + +prngLogNormal = d3Random.randomLogNormal; +prngLogNormal = d3Random.randomLogNormal.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngLogNormal(); +randomNumberGenerator = prngLogNormal(3); +randomNumberGenerator = prngLogNormal(3, 4); // ------------------------------------------------------------ // randomBates // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomBates(3); +let prngBates: d3Random.RandomBates; + +prngBates = d3Random.randomBates; +prngBates = d3Random.randomBates.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngBates(3); // ------------------------------------------------------------ // randomIrwinHall // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomIrwinHall(3); +let prngIrwinHall: d3Random.RandomIrwinHall; + +prngIrwinHall = d3Random.randomIrwinHall; +prngIrwinHall = d3Random.randomIrwinHall.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngIrwinHall(3); // ------------------------------------------------------------ // randomExponential // ------------------------------------------------------------ -randomNumberGenerator = d3Random.randomExponential(1 / 40); +let prngExponential: d3Random.RandomExponential; + +prngExponential = d3Random.randomExponential; +prngExponential = d3Random.randomExponential.source(seedrandom("Schroedinger's flea.")); + +randomNumberGenerator = prngExponential(1 / 40); diff --git a/types/d3-random/index.d.ts b/types/d3-random/index.d.ts index 48c9b245ed..41b6034215 100644 --- a/types/d3-random/index.d.ts +++ b/types/d3-random/index.d.ts @@ -1,55 +1,112 @@ -// Type definitions for D3JS d3-random module v1.0.1 +// Type definitions for D3JS d3-random module 1.1 // Project: https://github.com/d3/d3-random/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * Returns a function for generating random numbers with a uniform distribution). - * The minimum allowed value of a returned number is min, and the maximum is max. - * If min is not specified, it defaults to 0; if max is not specified, it defaults to 1. - * - * @param min The minimum allowed value of a returned number, defaults to 0. - * @param max The maximum allowed value of a returned number, defaults to 1. - */ -export function randomUniform(min?: number, max?: number): () => number; +// Last module patch version validated against: 1.1.0 + +export interface RandomNumberGenerationSource { + /** + * Returns the same type of function for generating random numbers but where the given random number + * generator source is used as the source of randomness instead of Math.random. + * This is useful when a seeded random number generator is preferable to Math.random. + * + * @param source Source (pseudo-)random number generator implementing the Math.random interface. + * The given random number generator must implement the same interface as Math.random and + * only return values in the range [0, 1). + */ + source(source: () => number): this; +} /** - * Returns a function for generating random numbers with a normal (Gaussian) distribution. - * The expected value of the generated numbers is mu, with the given standard deviation sigma. - * If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. - * - * @param mu Expected value, defaults to 0. - * @param sigma Standard deviation, defaults to 1. + * A configurable random number generator for the uniform distribution. */ -export function randomNormal(mu?: number, sigma?: number): () => number; +export interface RandomUniform extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a uniform distribution). + * The minimum allowed value of a returned number is min, and the maximum is max. + * If min is not specified, it defaults to 0; if max is not specified, it defaults to 1. + * + * @param min The minimum allowed value of a returned number, defaults to 0. + * @param max The maximum allowed value of a returned number, defaults to 1. + */ + (min?: number, max?: number): () => number; +} + +export const randomUniform: RandomUniform; /** - * Returns a function for generating random numbers with a log-normal distribution. The expected value of the random variable’s natural logrithm is mu, - * with the given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. - * - * @param mu Expected value, defaults to 0. - * @param sigma Standard deviation, defaults to 1. + * A configurable random number generator for the normal (Gaussian) distribution. */ -export function randomLogNormal(mu?: number, sigma?: number): () => number; +export interface RandomNormal extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a normal (Gaussian) distribution. + * The expected value of the generated numbers is mu, with the given standard deviation sigma. + * If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. + * + * @param mu Expected value, defaults to 0. + * @param sigma Standard deviation, defaults to 1. + */ + (mu?: number, sigma?: number): () => number; +} + +export const randomNormal: RandomNormal; /** - * Returns a function for generating random numbers with a Bates distribution with n independent variables. - * - * @param n Number of independent random variables to use. + * A configurable random number generator for the log-normal distribution. */ -export function randomBates(n: number): () => number; +export interface RandomLogNormal extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a log-normal distribution. The expected value of the random variable’s natural logrithm is mu, + * with the given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. + * + * @param mu Expected value, defaults to 0. + * @param sigma Standard deviation, defaults to 1. + */ + (mu?: number, sigma?: number): () => number; +} + +export const randomLogNormal: RandomLogNormal; /** - * Returns a function for generating random numbers with an Irwin–Hall distribution with n independent variables. - * - * @param n Number of independent random variables to use. + * A configurable random number generator for the Bates distribution. */ -export function randomIrwinHall(n: number): () => number; +export interface RandomBates extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a Bates distribution with n independent variables. + * + * @param n Number of independent random variables to use. + */ + (n: number): () => number; +} + +export const randomBates: RandomBates; /** - * Returns a function for generating random numbers with an exponential distribution with the rate lambda; - * equivalent to time between events in a Poisson process with a mean of 1 / lambda. - * - * @param lambda Expected time between events. + * A configurable random number generator for the Irwin–Hall distribution. */ -export function randomExponential(lambda: number): () => number; +export interface RandomIrwinHall extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with an Irwin–Hall distribution with n independent variables. + * + * @param n Number of independent random variables to use. + */ + (n: number): () => number; +} + +export const randomIrwinHall: RandomIrwinHall; + +/** + * A configurable random number generator for the exponential distribution. + */ +export interface RandomExponential extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with an exponential distribution with the rate lambda; + * equivalent to time between events in a Poisson process with a mean of 1 / lambda. + * + * @param lambda Expected time between events. + */ + (lambda: number): () => number; +} + +export const randomExponential: RandomExponential; diff --git a/types/d3-random/tsconfig.json b/types/d3-random/tsconfig.json index 20a20f04f1..f9544a0527 100644 --- a/types/d3-random/tsconfig.json +++ b/types/d3-random/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "d3-random-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/d3-random/tslint.json b/types/d3-random/tslint.json new file mode 100644 index 0000000000..4ae99abce4 --- /dev/null +++ b/types/d3-random/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": [false, 140] + } +} diff --git a/types/d3-sankey/d3-sankey-tests.ts b/types/d3-sankey/d3-sankey-tests.ts new file mode 100644 index 0000000000..246755a900 --- /dev/null +++ b/types/d3-sankey/d3-sankey-tests.ts @@ -0,0 +1,258 @@ +/** + * Typescript definition tests for d3/d3-sankey module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Sankey from 'd3-sankey'; +import {select, Selection} from 'd3-selection'; + +// --------------------------------------------------------------------------- +// Preparatory Steps +// --------------------------------------------------------------------------- + +// Create interfaces for the user-provided node/link attributes, which are NOT mandated or calculated by +// the Sankey layout generator. The latter are reflected in the SankeyNode and SankeyLink interfaces provided +// by the definitions file +interface SNodeExtra { + nodeId: number; + name: string; +} + +interface SLinkExtra { + uom: string; +} + +// For convenience +type SNode = d3Sankey.SankeyNode; +type SLink = d3Sankey.SankeyLink; + +interface DAG { + nodes: SNode[]; + links: SLink[]; +} + +const graph: DAG = { + nodes: [{ + nodeId: 0, + name: "node0" + }, { + nodeId: 1, + name: "node1" + }, { + nodeId: 2, + name: "node2" + }, { + nodeId: 3, + name: "node3" + }, { + nodeId: 4, + name: "node4" + }], + links: [{ + source: 0, + target: 2, + value: 2, + uom: 'Widget(s)' + }, { + source: 1, + target: 2, + value: 2, + uom: 'Widget(s)' + }, { + source: 1, + target: 3, + value: 2, + uom: 'Widget(s)' + }, { + source: 0, + target: 4, + value: 2, + uom: 'Widget(s)' + }, { + source: 2, + target: 3, + value: 2, + uom: 'Widget(s)' + }, { + source: 2, + target: 4, + value: 2, + uom: 'Widget(s)' + }, { + source: 3, + target: 4, + value: 4, + uom: 'Widget(s)' + }] +}; + +let sNodes: SNode[]; +let sLinks: SLink[]; + +let num: number; +let numMaybe: number | undefined; +let str: string; +let size: [number, number]; + +const svgLinkPaths = select('svg').selectAll('.linkPath'); // assume mock DOM + +// --------------------------------------------------------------------------- +// Obtain SankeyLayout Generator +// --------------------------------------------------------------------------- + +let slgDefault: d3Sankey.SankeyLayout<{}, {}> = d3Sankey.sankey(); +let slgDAG: d3Sankey.SankeyLayout = d3Sankey.sankey(); + +// --------------------------------------------------------------------------- +// NodeWidth +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodeWidth(32); + +// Get ----------------------------------------------------------------------- + +num = slgDAG.nodeWidth(); + +// --------------------------------------------------------------------------- +// NodePadding +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodePadding(8); + +// Get ----------------------------------------------------------------------- + +num = slgDAG.nodePadding(); + +// --------------------------------------------------------------------------- +// Size +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.size([1200, 800]); + +// Get ----------------------------------------------------------------------- + +size = slgDAG.size(); + +// --------------------------------------------------------------------------- +// Nodes +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodes(graph.nodes); + +// Get ----------------------------------------------------------------------- + +sNodes = slgDAG.nodes(); + +// --------------------------------------------------------------------------- +// Links +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.links(graph.links); + +// Get ----------------------------------------------------------------------- + +sLinks = slgDAG.links(); + +// --------------------------------------------------------------------------- +// Compute Layout +// --------------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.layout(22); + +// --------------------------------------------------------------------------- +// Relayout +// --------------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.relayout(); + +// --------------------------------------------------------------------------- +// Obtain and Use Link SVG Path Generator +// --------------------------------------------------------------------------- + +let pathGen: d3Sankey.SankeyLinkPathGenerator; + +pathGen = slgDAG.link(); + +// Adjust Link SVG Path Generator curvature ---------------------------------- + +// test return type +pathGen = pathGen.curvature(0.6); +num = pathGen.curvature(); + +// uses + +let svgPathString: string = pathGen(slgDAG.links()[0]); +svgLinkPaths.attr('d', pathGen); + +// --------------------------------------------------------------------------- +// Shape test Node/Link related interfaces and types +// --------------------------------------------------------------------------- + +// Sankey Node -------------------------------------------------------------- + +let sNode = sNodes[0]; + +// User-specified extra properties: + +num = sNode.nodeId; +str = sNode.name; + +// Sankey Layout calculated (if layout has been run, otherwise undefined): + +numMaybe = sNode.dx; +numMaybe = sNode.x; +numMaybe = sNode.dy; +numMaybe = sNode.y; +numMaybe = sNode.value; + +let linksArrMaybe: SLink[] | undefined; + +linksArrMaybe = sNode.sourceLinks; +linksArrMaybe = sNode.targetLinks; + +// Sankey Link -------------------------------------------------------------- + +let sLink = sLinks[0]; + +// User-specified extra properties: + +str = sLink.uom; + +// Sankey Layout mandated link properties: + +num = sLink.value; + +// Node depending on initialization strategy and whether +// layout(...) was invoked, the source and target nodes may be numbers +// objects without the Sankey layout coordinates, or objects with calculated +// information +let numOrSankeyNode: number | SNode; + +numOrSankeyNode = sLink.source; +numOrSankeyNode = sLink.target; + +// Sankey Layout calculated (if layout has been run, otherwise undefined): + +numMaybe = sLink.sy; +numMaybe = sLink.ty; +numMaybe = sLink.dy; diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts new file mode 100644 index 0000000000..1446bc917f --- /dev/null +++ b/types/d3-sankey/index.d.ts @@ -0,0 +1,267 @@ +// Type definitions for D3JS d3-sankey module 0.4 +// Project: https://github.com/d3/d3-sankey/ +// Definitions by: Tom Wanzek , Alex Ford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Last module patch version validated against: 0.4.2 + +/** + * A helper interface as an extension reference for user-provided properties of + * nodes and links in the graph, which are not required or calculated by + * the Sankey Layout Generator + */ +export interface SankeyExtraProperties { [key: string]: any; } + +/** + * Helper interface to define the properties of Sankey Nodes. Calculated properties may only be defined, + * once the layout(...) method of the Sankey layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyNodeMinimal { + /** + * Array of links which have this node as their source. + * This property is calculated internally by the Sankey layout generator. + */ + sourceLinks?: Array>; + /** + * Array of links which have this node as their target. + * This property is calculated internally by the Sankey layout generator. + */ + targetLinks?: Array>; + /** + * Node value calculated by Sankey Layout Generator based on values of incoming and outgoing links + */ + value?: number; + /** + * Node horizontal position calculated by Sankey layout generator + */ + x?: number; + /** + * Node width calculated by Sankey layout generator + */ + dx?: number; + /** + * Node vertical position (depth) calculated by Sankey layout generator + */ + y?: number; + /** + * Node height (vertical extent based on node value) calculated by Sankey layout generator + */ + dy?: number; +} + +/** + * Sankey Node type including both user-defined node data elements as well as those + * calculated once the layout(...) method of the Sankey layout generators has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export type SankeyNode = N & SankeyNodeMinimal; + +/** + * Helper interface to define the properties of Sankey Links. Calculated properties may only be defined, + * once the layout(...) method of the Sankey layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyLinkMinimal { + /** + * Source node of the link. For convenience, when initializing a Sankey layout, source may be the index of the source node in the nodes array + * passed into the Sankey layout generator. Once the layout(...) method is invoked, the numeric index will be replaced with the corresponding + * source node object. + */ + source: number | SankeyNode; + /** + * Target node of the link. For convenience, when initializing a Sankey layout, target may be the index of the target node in the nodes array + * passed into the Sankey layout generator. Once the layout(...) method is invoked, the numeric index will be replaced with the corresponding + * target node object. + */ + target: number | SankeyNode; + /** + * Value of the link + */ + value: number; + /** + * Link breadth calculated by Sankey layout generator based on the link value + */ + dy?: number; + /** + * Vertical starting position of the link (at source node) calculated by Sankey layout generator + */ + sy?: number; + /** + * Vertical end position of the link (at target node) calculated by Sankey layout generator + */ + ty?: number; +} + +/** + * Sankey Link type including both user-defined link data elements, those required by the Sankey layout generator, + * as well as those calculated once the layout(...) method of the layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export type SankeyLink = L & SankeyLinkMinimal; + +/** + * An svg path generator factory for the link paths in a calculated Sankey Layout. + */ +export interface SankeyLinkPathGenerator { + /** + * Return svg path string for a given link. + * + * IMPORTANT: Only invoke for link data with Sankey Layout information previously calculated. + * + * @param link A Sankey diagram link, for which the layout has already been calculated. + */ + (link: SankeyLink): string; + /** + * Returns the current curvature used to calculate svg paths for links. + * The default curvature is 0.5. + */ + curvature(): number; + /** + * Set the curvature used to calculate svg paths for links and return the updated link path generator. + * + * @param curvature Curvature to be used when calculating svg paths for links. The default curvature is 0.5. + */ + curvature(curvature: number): this; +} + +/** + * A Sankey layout generator. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyLayout { + /** + * Return the current node width, which defaults to 24. + */ + nodeWidth(): number; + /** + * Set the node width to the specified number and return this Sankey layout generator. + * + * @param width Width of node in pixels, which defaults to 24. + */ + nodeWidth(width: number): this; + + /** + * Return the current node padding, which defaults to 8. + * + * Node padding refers to the vertical space between nodes which occupy the same horizontal space. + */ + nodePadding(): number; + /** + * Set the node padding to the specified number and return this Sankey layout generator. + * + * Node padding refers to the vertical space between nodes which occupy the same horizontal space. + * + * @param padding Node padding in pixels, which defaults to 8. + */ + nodePadding(padding: number): this; + + /** + * Return the current array of nodes, which defaults to []. + */ + nodes(): Array>; + /** + * Set the sankey generator's nodes to the specified array of objects and returns this sankey layout generator. + * + * @param nodes Array of nodes. + */ + nodes(nodes: Array>): this; + + /** + * Return the current array of links, which defaults to []. + */ + links(): Array>; + /** + * Set the sankey generator's links to the specified array of objects and returns this sankey layout generator. + * + * @param links Array of links. + */ + links(links: Array>): this; + + /** + * Runs the sankey layout algorithm updating the nodes and links with their respective layout information and returns this sankey generator. + * + * @param iterations Number of passes to be used in the iterative relaxation algorithm for node placement. + */ + layout(iterations: number): this; + + /** + * Recalculate the depth of links and return this Sankey layout generator. + * This methods is primarily used when a node is moved vertically, e.g. using d3-drag. + */ + relayout(): this; + + /** + * Return the current layout size in pixels. The size is a two element array of [width, height] which defaults to [1, 1]. + */ + size(): [number, number]; + /** + * Set the size of the layout and return this Sankey layout generator. + * + * @param size A two element array of [width, height] in pixels which defaults to [1, 1]. + */ + size(size: [number, number]): this; + + /** + * Return a Sankey link path generator for the links based on the calculated Sankey diagram layout. + * The link path generator can be invoked as a function being passed as its argument a link object + * with calculated layout information. It returns the computed path string for the link. + * By default the link path generator uses a curvature of 0.5. + */ + link(): SankeyLinkPathGenerator; +} + +/** + * Get a Sankey layout generator. + * + * Invoking sankey() without generics, means the node type and link type assume no user-defined attributes, i.e. + * only the attributes internally used by the Sankey layout generator. + */ +export function sankey(): SankeyLayout<{}, {}>; +/** + * Get a Sankey layout generator. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export function sankey(): SankeyLayout; diff --git a/types/d3-sankey/tsconfig.json b/types/d3-sankey/tsconfig.json new file mode 100644 index 0000000000..bd11293dc2 --- /dev/null +++ b/types/d3-sankey/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-sankey-tests.ts" + ] +} diff --git a/types/d3-sankey/tslint.json b/types/d3-sankey/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/d3-sankey/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index b583bfc8b6..09974bf299 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -165,6 +165,12 @@ svgZoom = svgZoom.translateExtent([[-500, -500], [500, 500]]); let translateExtent: [[number, number], [number, number]]; translateExtent = svgZoom.translateExtent(); +// clickDistance() --------------------------------------------------------- + +svgZoom = svgZoom.clickDistance(5); + +const distance: number = svgZoom.clickDistance(); + // duration() -------------------------------------------------------------- // chainable diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index 62c49b977b..88a9a7b95f 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.1 +// Type definitions for d3JS d3-zoom module 1.2 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.1 +// Last module patch version validated against: 1.2.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -461,6 +461,20 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/deepmerge/deepmerge-tests.ts b/types/deepmerge/deepmerge-tests.ts index 8c7988ba78..5467cb83f0 100644 --- a/types/deepmerge/deepmerge-tests.ts +++ b/types/deepmerge/deepmerge-tests.ts @@ -1,13 +1,19 @@ import * as deepmerge from "deepmerge"; -const x = { foo: { bar: 3 }, - array: [ { does: 'work', too: [ 1, 2, 3 ] } ] }; -const y = { foo: { baz: 4 }, +const x = { + foo: { bar: 3 }, + array: [{ does: 'work', too: [1, 2, 3] }] +}; +const y = { + foo: { baz: 4 }, quux: 5, - array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] }; + array: [{ does: 'work', too: [4, 5, 6] }, { really: 'yes' }] +}; -const expected = { foo: { bar: 3, baz: 4 }, - array: [ { does: 'work', too: [ 1, 2, 3, 4, 5, 6 ] }, { really: 'yes' } ], - quux: 5 }; +const expected = { + foo: { bar: 3, baz: 4 }, + array: [{ does: 'work', too: [1, 2, 3, 4, 5, 6] }, { really: 'yes' }], + quux: 5 +}; const result = deepmerge(x, y); diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 36edef83b3..e1b1025495 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -1,13 +1,11 @@ - - +// tslint:disable:no-var only-arrow-functions import jsdiff = require('diff'); - var one = 'beep boop'; var other = 'beep boob blah'; var diff = jsdiff.diffChars(one, other); -diff.forEach(function (part) { +diff.forEach(function(part) { var mark = part.added ? '+' : part.removed ? '-' : ' '; console.log(mark + " " + part.value); @@ -16,11 +14,11 @@ diff.forEach(function (part) { // -------------------------- class LineDiffWithoutWhitespace extends jsdiff.Diff { - tokenize(value:string):any { + tokenize(value: string): any { return value.split(/^/m); } - equals(left:string, right:string):boolean { + equals(left: string, right: string): boolean { return left.trim() === right.trim(); } } @@ -29,8 +27,8 @@ var obj = new LineDiffWithoutWhitespace(true); var diff = obj.diff(one, other); printDiff(diff); -function printDiff(diff:jsdiff.IDiffResult[]) { - function addLineHeader(decorator:string, str:string) { +function printDiff(diff: jsdiff.IDiffResult[]) { + function addLineHeader(decorator: string, str: string) { return str.split("\n").map((line, index, array) => { if (index === array.length - 1 && line === "") { return line; @@ -40,7 +38,7 @@ function printDiff(diff:jsdiff.IDiffResult[]) { }).join("\n"); } - diff.forEach((part)=> { + diff.forEach((part) => { if (part.added) { console.log(addLineHeader("+", part.value)); } else if (part.removed) { diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 102305ce70..03228269e0 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for diff +// Type definitions for diff 3.2 // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 export = JsDiff; export as namespace JsDiff; @@ -36,34 +37,37 @@ declare namespace JsDiff { } class Diff { - ignoreWhitespace:boolean; + ignoreWhitespace: boolean; - constructor(ignoreWhitespace?:boolean); + constructor(ignoreWhitespace?: boolean); - diff(oldString:string, newString:string):IDiffResult[]; + diff(oldString: string, newString: string): IDiffResult[]; - pushComponent(components:IDiffResult[], value:string, added:boolean, removed:boolean):void; + pushComponent(components: IDiffResult[], value: string, added: boolean, removed: boolean): void; - extractCommon(basePath:IBestPath, newString:string, oldString:string, diagonalPath:number):number; + extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; - equals(left:string, right:string):boolean; + equals(left: string, right: string): boolean; - join(left:string, right:string):string; + join(left: string, right: string): string; - tokenize(value:string):any; // return types are string or string[] + tokenize(value: string): any; // return types are string or string[] } - function diffChars(oldStr:string, newStr:string):IDiffResult[]; + function diffChars(oldStr: string, newStr: string): IDiffResult[]; - function diffWords(oldStr:string, newStr:string):IDiffResult[]; + function diffWords(oldStr: string, newStr: string): IDiffResult[]; - function diffWordsWithSpace(oldStr:string, newStr:string):IDiffResult[]; + function diffWordsWithSpace(oldStr: string, newStr: string): IDiffResult[]; - function diffJson(oldObj: Object, newObj: Object): IDiffResult[]; + function diffJson(oldObj: object, newObj: object): IDiffResult[]; - function diffLines(oldStr:string, newStr:string):IDiffResult[]; + function diffLines(oldStr: string, newStr: string, options?: { + ignoreWhitespace?: boolean, + newlineIsToken?: boolean, + }): IDiffResult[]; - function diffCss(oldStr:string, newStr:string):IDiffResult[]; + function diffCss(oldStr: string, newStr: string): IDiffResult[]; function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; @@ -74,14 +78,14 @@ declare namespace JsDiff { function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; function applyPatches(uniDiff: IUniDiff[], options: { - loadFile: (index: number, callback: (err: Error, data: string) => void) => void, - patched: (index: number, content: string) => void, - complete: (err?: Error) => void + loadFile(index: number, callback: (err: Error, data: string) => void): void, + patched(index: number, content: string): void, + complete(err?: Error): void }): void; function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; - function convertChangesToXML(changes:IDiffResult[]):string; + function convertChangesToXML(changes: IDiffResult[]): string; - function convertChangesToDMP(changes:IDiffResult[]):{0: number; 1:string;}[]; + function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; } diff --git a/types/diff/tslint.json b/types/diff/tslint.json new file mode 100644 index 0000000000..1b7b2672e6 --- /dev/null +++ b/types/diff/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-name": false, + "export-just-namespace": false + } +} diff --git a/types/dockerode/dockerode-tests.ts b/types/dockerode/dockerode-tests.ts index 4b4e406839..8dd9a380de 100644 --- a/types/dockerode/dockerode-tests.ts +++ b/types/dockerode/dockerode-tests.ts @@ -24,6 +24,25 @@ const docker6 = new Docker({ key: 'key' }); +const docker7 = new Docker({ + Promise +}); + +async function foo() { + const containers = await docker7.listContainers(); + for (const container of containers) { + const foo = await docker7.getContainer(container.Id); + const inspect = await foo.inspect(); + } + + const images = await docker5.listImages(); + for (const image of images) { + const foo = await docker5.getImage(image.Id); + const inspect = await foo.inspect(); + await foo.remove(); + } +} + const container = docker.getContainer('container-id'); container.inspect((err, data) => { // NOOP @@ -47,6 +66,10 @@ docker.listContainers((err, containers) => { }); }); +docker.listContainers().then(containers => { + return containers.map(container => docker.getContainer(container.Id)); +}); + docker.buildImage('archive.tar', { t: 'imageName' }, (err, response) => { // NOOP }); diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 2e834f0b3b..a4a1144872 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -12,69 +12,93 @@ declare namespace Dockerode { interface Container { inspect(options: {}, callback: Callback): void; inspect(callback: Callback): void; - inspect(options?: {}): { id: string }; + inspect(options?: {}): Promise; rename(options: {}, callback: Callback): void; + rename(options: {}): Promise; update(options: {}, callback: Callback): void; + update(options: {}): Promise; top(options: {}, callback: Callback): void; top(callback: Callback): void; + top(options?: {}): Promise; changes(callback: Callback): void; + changes(): Promise; export(callback: Callback): void; + export(): Promise; start(options: {}, callback: Callback): void; start(callback: Callback): void; + start(options?: {}): Promise; pause(options: {}, callback: Callback): void; pause(callback: Callback): void; + pause(options?: {}): Promise; unpause(options: {}, callback: Callback): void; unpause(callback: Callback): void; + unpause(options?: {}): Promise; exec(options: {}, callback: Callback): void; + exec(options: {}): Promise; commit(options: {}, callback: Callback): void; commit(callback: Callback): void; + commit(options?: {}): Promise; stop(options: {}, callback: Callback): void; stop(callback: Callback): void; + stop(options?: {}): Promise; restart(options: {}, callback: Callback): void; restart(callback: Callback): void; + restart(options?: {}): Promise; kill(options: {}, callback: Callback): void; kill(callback: Callback): void; + kill(options?: {}): Promise; resize(options: {}, callback: Callback): void; resize(callback: Callback): void; + resize(options?: {}): Promise; wait(callback: Callback): void; + wait(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; /** Deprecated since RAPI v1.20 */ copy(options: {}, callback: Callback): void; /** Deprecated since RAPI v1.20 */ copy(callback: Callback): void; + /** Deprecated since RAPI v1.20 */ + copy(options?: {}): Promise; getArchive(options: {}, callback: Callback): void; + getArchive(options: {}): Promise; infoArchive(options: {}, callback: Callback): void; + infoArchive(options: {}): Promise; /** @param file Filename (will read synchronously), Buffer or stream */ putArchive(file: string | Buffer | NodeJS.ReadableStream, options: {}, callback: Callback): void; + putArchive(file: string | Buffer | NodeJS.ReadableStream, options: {}): Promise; - logs(options: { stdout?: boolean, stderr?: boolean, follow?: boolean, since?: number, details?: boolean, tail?: number, timestamps?: boolean }, callback: Callback): void; + logs(options: ContainerLogsOptions, callback: Callback): void; logs(callback: Callback): void; + logs(options?: ContainerLogsOptions): Promise; stats(options: {}, callback: Callback): void; stats(callback: Callback): void; + stats(options?: {}): Promise; attach(options: {}, callback: Callback): void; + attach(options: {}): Promise; modem: any; id?: string; @@ -82,19 +106,25 @@ declare namespace Dockerode { interface Image { inspect(callback: Callback): void; + inspect(): Promise; history(callback: Callback): void; + history(): Promise; get(callback: Callback): void; + get(): Promise; push(options: {}, callback: Callback): void; push(callback: Callback): void; + push(options?: {}): Promise; tag(options: {}, callback: Callback): void; tag(callback: Callback): void; + tag(options?: {}): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; modem: any; id?: string; @@ -102,9 +132,11 @@ declare namespace Dockerode { interface Volume { inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; modem: any; name?: string; @@ -112,11 +144,14 @@ declare namespace Dockerode { interface Service { inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; update(options: {}, callback: Callback): void; + update(options: {}): Promise; modem: any; id?: string; @@ -124,6 +159,7 @@ declare namespace Dockerode { interface Task { inspect(callback: Callback): void; + inspect(): Promise; modem: any; id?: string; @@ -131,6 +167,7 @@ declare namespace Dockerode { interface Node { inspect(callback: Callback): void; + inspect(): Promise; modem: any; id?: string; @@ -142,38 +179,50 @@ declare namespace Dockerode { remote: any; inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; privileges(callback: Callback): void; + privileges(): Promise; pull(options: {}, callback: Callback): void; + pull(options: {}): Promise; enable(options: {}, callback: Callback): void; enable(callback: Callback): void; + enable(options?: {}): Promise; disable(options: {}, callback: Callback): void; disable(callback: Callback): void; + disable(options?: {}): Promise; push(options: {}, callback: Callback): void; push(callback: Callback): void; + push(options?: {}): Promise; configure(options: {}, callback: Callback): void; configure(callback: Callback): void; + configure(options?: {}): Promise; upgrade(auth: any, options: {}, callback: Callback): void; upgrade(auth: any, callback: Callback): void; + upgrade(auth: any, options?: {}): Promise; } interface Secret { inspect(callback: Callback): void; + inspect(): Promise; update(options: {}, callback: Callback): void; update(callback: Callback): void; + update(options?: {}): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; modem: any; id?: string; @@ -181,15 +230,19 @@ declare namespace Dockerode { interface Network { inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; + remove(options?: {}): Promise; connect(options: {}, callback: Callback): void; connect(callback: Callback): void; + connect(options?: {}): Promise; disconnect(options: {}, callback: Callback): void; disconnect(callback: Callback): void; + disconnect(options?: {}): Promise; modem: any; id?: string; @@ -197,10 +250,13 @@ declare namespace Dockerode { interface Exec { inspect(callback: Callback): void; + inspect(): Promise; start(options: {}, callback: Callback): void; + start(options: {}): Promise; resize(options: {}, callback: Callback): void; + resize(options: {}): Promise; modem: any; id?: string; @@ -587,6 +643,7 @@ declare namespace Dockerode { key?: string; protocol?: "https" | "http"; timeout?: number; + Promise?: typeof Promise; } interface SecretVersion { @@ -719,6 +776,16 @@ declare namespace Dockerode { interface PruneNetworksInfo { NetworksDeleted: string[]; } + + interface ContainerLogsOptions { + stdout?: boolean; + stderr?: boolean; + follow?: boolean; + since?: number; + details?: boolean; + tail?: number; + timestamps?: boolean; + } } type Callback = (error?: any, result?: T) => void; @@ -727,20 +794,27 @@ declare class Dockerode { constructor(options?: Dockerode.DockerOptions); createContainer(options: Dockerode.ContainerCreateOptions, callback: Callback): void; + createContainer(options: Dockerode.ContainerCreateOptions): Promise; createImage(options: {}, callback: Callback): void; createImage(auth: any, options: {}, callback: Callback): void; + createImage(options: {}): Promise; + createImage(auth: any, options: {}): Promise; loadImage(file: string, options: {}, callback: Callback): void; loadImage(file: string, callback: Callback): void; + loadImage(file: string, options?: {}): Promise; importImage(file: string, options: {}, callback: Callback): void; importImage(file: string, callback: Callback): void; + importImage(file: string, options?: {}): Promise; checkAuth(options: any, callback: Callback): void; + checkAuth(options: any): Promise; buildImage(file: string | NodeJS.ReadableStream, options: {}, callback: Callback): void; buildImage(file: string | NodeJS.ReadableStream, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream, options?: {}): Promise; getContainer(id: string): Dockerode.Container; @@ -764,80 +838,110 @@ declare class Dockerode { listContainers(options: {}, callback: Callback): void; listContainers(callback: Callback): void; + listContainers(options?: {}): Promise; listImages(options: {}, callback: Callback): void; listImages(callback: Callback): void; + listImages(options?: {}): Promise; listServices(options: {}, callback: Callback): void; listServices(callback: Callback): void; + listServices(options?: {}): Promise; listNodes(options: {}, callback: Callback): void; listNodes(callback: Callback): void; + listNodes(options?: {}): Promise; listTasks(options: {}, callback: Callback): void; listTasks(callback: Callback): void; + listTasks(options?: {}): Promise; listSecrets(options: {}, callback: Callback): void; listSecrets(callback: Callback): void; + listSecrets(options?: {}): Promise; listPlugins(options: {}, callback: Callback): void; listPlugins(callback: Callback): void; + listPlugins(options?: {}): Promise; listVolumes(options: {}, callback: Callback): void; listVolumes(callback: Callback): void; + listVolumes(options?: {}): Promise; listNetworks(options: {}, callback: Callback): void; listNetworks(callback: Callback): void; + listNetworks(options?: {}): Promise; createSecret(options: {}, callback: Callback): void; + createSecret(options: {}): Promise; createPlugin(options: {}, callback: Callback): void; + createPlugin(options: {}): Promise; createVolume(options: {}, callback: Callback): void; + createVolume(options: {}): Promise; createService(options: {}, callback: Callback): void; + createService(options: {}): Promise; createNetwork(options: {}, callback: Callback): void; + createNetwork(options: {}): Promise; searchImages(options: {}, callback: Callback): void; + searchImages(options: {}): Promise; pruneImages(options: {}, callback: Callback): void; pruneImages(callback: Callback): void; + pruneImages(options?: {}): Promise; pruneContainers(options: {}, callback: Callback): void; pruneContainers(callback: Callback): void; + pruneContainers(options?: {}): Promise; pruneVolumes(options: {}, callback: Callback): void; pruneVolumes(callback: Callback): void; + pruneVolumes(options?: {}): Promise; pruneNetworks(options: {}, callback: Callback): void; pruneNetworks(callback: Callback): void; + pruneNetworks(options?: {}): Promise; info(callback: Callback): void; + info(): Promise; version(callback: Callback): void; + version(): Promise; ping(callback: Callback): void; + ping(): Promise; getEvents(options: {}, callback: Callback): void; getEvents(callback: Callback): void; + getEvents(options?: {}): Promise; pull(repoTag: string, options: {}, callback: Callback, auth?: {}): Dockerode.Image; + pull(repoTag: string, options: {}, auth?: {}): Promise; run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, startOptions: {}, callback: Callback): events.EventEmitter; run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, startOptions: {}, callback: Callback): events.EventEmitter; run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, callback: Callback): events.EventEmitter; run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions?: {}, startOptions?: {}): Promise; swarmInit(options: {}, callback: Callback): void; + swarmInit(options: {}): Promise; swarmJoin(options: {}, callback: Callback): void; + swarmJoin(options: {}): Promise; swarmLeave(options: {}, callback: Callback): void; + swarmLeave(options: {}): Promise; swarmUpdate(options: {}, callback: Callback): void; + swarmUpdate(options: {}): Promise; swarmInspect(callback: Callback): void; + swarmInspect(): Promise; modem: any; } diff --git a/types/dockerode/tsconfig.json b/types/dockerode/tsconfig.json index 2a83a71968..8f360ab29a 100644 --- a/types/dockerode/tsconfig.json +++ b/types/dockerode/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { + "target": "es6", "module": "commonjs", "lib": [ "es6" diff --git a/types/dotenv/dotenv-tests.ts b/types/dotenv/dotenv-tests.ts index f609dd4745..df05475c17 100644 --- a/types/dotenv/dotenv-tests.ts +++ b/types/dotenv/dotenv-tests.ts @@ -1,15 +1,7 @@ import dotenv = require('dotenv'); -// typically, result will be an Object -const env = dotenv.config({ - silent: true -}); -const dbUrl: string | null = !env ? null : env['DATABASE_URL']; - -// ... but it might also be `false` -const result = dotenv.config({ - path: '.non-existing-env' -}); +const env = dotenv.config(); +const dbUrl: string | null = env.error || !env.parsed ? null : env.parsed['DATABASE_URL']; dotenv.config({ path: '.env' diff --git a/types/dotenv/index.d.ts b/types/dotenv/index.d.ts index 7e015ca8cd..92e15c1637 100644 --- a/types/dotenv/index.d.ts +++ b/types/dotenv/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dotenv 2.0 +// Type definitions for dotenv 4.0 // Project: https://github.com/motdotla/dotenv // Definitions by: Jussi Kinnula , Borek Bernard , Eric Naeseth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,18 +14,15 @@ export function parse(src: string | Buffer): {[name: string]: string}; * Loads `.env` into `process.env`. * * @param options - * @return Object Object with the parsed keys and values, e.g., 'KEY=value' becomes { KEY: 'value' } + * @return Object Object with either + * - "parsed" containing the parsed keys and values or + * - "error" containing an Error object + * + * Example: 'KEY=value' becomes { parsed: { KEY: 'value' } } */ -export function config(options?: DotenvOptions): {[name: string]: string} | false; +export function config(options?: DotenvOptions): DotenvResult; 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. * @@ -40,3 +37,10 @@ export interface DotenvOptions { */ encoding?: string; } + +export interface DotenvResult { + error?: Error; + parsed?: { + [name: string]: string; + }; +} diff --git a/types/dotenv/v2/dotenv-tests.ts b/types/dotenv/v2/dotenv-tests.ts new file mode 100644 index 0000000000..f609dd4745 --- /dev/null +++ b/types/dotenv/v2/dotenv-tests.ts @@ -0,0 +1,26 @@ +import dotenv = require('dotenv'); + +// typically, result will be an Object +const env = dotenv.config({ + silent: true +}); +const dbUrl: string | null = !env ? null : env['DATABASE_URL']; + +// ... but it might also be `false` +const result = dotenv.config({ + path: '.non-existing-env' +}); + +dotenv.config({ + path: '.env' +}); + +dotenv.config({ + encoding: 'utf8' +}); + +const parsed = dotenv.parse("ENVIRONMENT=production\nDEBUG=no\n"); +const debug: string = parsed['DEBUG']; + +const parsedFromBuffer = dotenv.parse(new Buffer("JUSTICE=league\n")); +const justice: string = parsedFromBuffer['JUSTICE']; diff --git a/types/dotenv/v2/index.d.ts b/types/dotenv/v2/index.d.ts new file mode 100644 index 0000000000..7e015ca8cd --- /dev/null +++ b/types/dotenv/v2/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for dotenv 2.0 +// Project: https://github.com/motdotla/dotenv +// Definitions by: Jussi Kinnula , Borek Bernard , Eric Naeseth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Parses a string or buffer in the .env file format into an object. + */ +export function parse(src: string | Buffer): {[name: string]: string}; + +/** + * 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): {[name: string]: string} | false; + +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/types/dotenv/v2/tsconfig.json b/types/dotenv/v2/tsconfig.json new file mode 100644 index 0000000000..efaf5860d4 --- /dev/null +++ b/types/dotenv/v2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "dotenv": [ "dotenv/v2" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dotenv-tests.ts" + ] +} diff --git a/types/dotenv/v2/tslint.json b/types/dotenv/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotenv/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dottie/dottie-tests.ts b/types/dottie/dottie-tests.ts new file mode 100644 index 0000000000..366d2e32d9 --- /dev/null +++ b/types/dottie/dottie-tests.ts @@ -0,0 +1,21 @@ +import dottie = require('dottie'); + +dottie.memoizePath = true; + +const nestedObject = { + some: { + nested: { + value: 'a' + } + } +}; + +dottie.exists(nestedObject, 'some.nested'); +dottie.default(nestedObject, 'some.nested.value', 'b'); +dottie.get(nestedObject, 'some.nested.value', 'b'); +dottie.set(nestedObject, 'some.nested.value', 'b'); +dottie.transform({ 'foo.bar': 'baz' }); +dottie.transform({ foo_bar: 'baz' }, { delimiter: '_' }); +dottie.flatten({ foo: { bar: 'baz' }}); +dottie.flatten({ foo: { bar: 'baz' }}, '_'); +dottie.paths(nestedObject); diff --git a/types/dottie/index.d.ts b/types/dottie/index.d.ts new file mode 100644 index 0000000000..66fb81df5f --- /dev/null +++ b/types/dottie/index.d.ts @@ -0,0 +1,194 @@ +// Type definitions for dottie 2.0 +// Project: https://github.com/mickhansen/dottie +// Definitions by: Dom Armstrong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare const dottie: dottie.Dottie; +export = dottie; + +declare namespace dottie { + type DottiePath = string | string[]; + + /** + * @example: + * { + * 'foo.bar.baz': 'baz', + * 'foo.baz': 'baz', + * } + */ + interface FlatPaths { + [path: string]: any; + } + + interface SetOptions { + /** + * force overwrite defined non-object keys into objects if needed + */ + force?: boolean; + } + + interface TransformOptions { + /** + * Use a custom delimiter for path + */ + delimiter?: string; + } + + interface Dottie { + /** + * Dottie memoization flag + */ + memoizePath: boolean; + + /** + * Check path exists in object + * + * @example + * const values = { + * some: { + * key: 'foobar'; + * }, + * } + * + * dottie.exists(values, 'some.key'); // true + * dottie.exists(values, 'some.otherKey'); // false + */ + exists(obj: object, path: DottiePath): boolean; + + /** + * Gets nested value, or undefined if unreachable, or a default value if passed. + * + * @example + * const values = { + * some: { + * nested: { + * key: 'foobar'; + * } + * }, + * 'some.dot.included': { + * key: 'barfoo' + * } + * } + * + * dottie.get(values, 'some.nested.key'); // 'foobar' + * dottie.get(values, 'some.undefined.key'); // undefined + * dottie.get(values, 'some.undefined.key', 'defaultval'); // 'defaultval' + * dottie.get(values, ['some.dot.included', 'key']); // 'barfoo' + */ + get(obj: object, path: DottiePath, defaultValue: T): T; + + /** + * Sets nested value, creates nested structure if needed + * + * @example + * dottie.set(values, 'some.nested.value', someValue); + * dottie.set(values, ['some.dot.included', 'value'], someValue); + * dottie.set(values, 'some.nested.object', someValue, { force: true }); + */ + set(obj: object, path: DottiePath, value: any, options?: SetOptions): void; + + /** + * Set the default value if path does not exist + * + * @example + * dottie.default({}, 'some.value', 'a') as MyType; // { some: { value: 'a' }} + * dottie.default({ some: { value: 'a' }}, 'some.value', 'b') as MyType; // { some: { value: 'a' }} + */ + default(obj: object, path: DottiePath, value: any): any; + + /** + * Transform object from keys with dottie notation to nested objects + * + * @example + * const values = { + * 'user.name': 'Gummy Bear', + * 'user.email': 'gummybear@candymountain.com', + * 'user.professional.title': 'King', + * 'user.professional.employer': 'Candy Mountain' + * }; + * const transformed = dottie.transform(values) as MyType; + * + * assert.deepEqual(transformed, { + * user: { + * name: 'Gummy Bear', + * email: 'gummybear@candymountain.com', + * professional: { + * title: 'King', + * employer: 'Candy Mountain' + * } + * } + * }); + * + * @example with custom delimiter + * const values = { + * 'user_name': 'Mick Hansen', + * 'user_email': 'maker@mhansen.io' + * }; + * const transformed = dottie.transform(values, { delimiter: '_' }) as MyType; + * + * assert.deepEqual(transformed, { + * user: { + * name: 'Mick Hansen', + * email: 'maker@mhansen.io' + * } + * }); + */ + transform(obj: FlatPaths, options?: TransformOptions): any; + + /** + * Opposite of transform. Flattens a nested object + * + * @example + * const values = { + * user: { + * name: 'Gummy Bear', + * email: 'gummybear@candymountain.com', + * professional: { + * title: 'King', + * employer: 'Candy Mountain' + * } + * } + * }; + * const transformed = dottie.transform(values); + * + * assert.deepEqual(transformed, { + * 'user.name': 'Gummy Bear', + * 'user.email': 'gummybear@candymountain.com', + * 'user.professional.title': 'King', + * 'user.professional.employer': 'Candy Mountain' + * }); + * + * @example with custom delimiter + * const values = { + * user: { + * name: 'Mick Hansen', + * email: 'maker@mhansen.io' + * } + * }; + * const transformed = dottie.flatten(values, '_'); + * + * assert.deepEqual(transformed, { + * 'user_name': 'Mick Hansen', + * 'user_email': 'maker@mhansen.io' + * }); + */ + flatten(obj: object, delimiter?: string): FlatPaths; + + /** + * Get paths in object + * + * @example + * const object = { + * a: 1, + * b: { + * c: 2, + * d: { e: 3 } + * } + * }; + * + * dottie.paths(object); // ["a", "b.c", "b.d.e"]; + */ + paths(obj: object): string[]; + } +} diff --git a/types/dottie/tsconfig.json b/types/dottie/tsconfig.json new file mode 100644 index 0000000000..03af0fda9b --- /dev/null +++ b/types/dottie/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dottie-tests.ts" + ] +} diff --git a/types/dottie/tslint.json b/types/dottie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dottie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dwt/dwt-tests.ts b/types/dwt/dwt-tests.ts new file mode 100644 index 0000000000..4b201cf33d --- /dev/null +++ b/types/dwt/dwt-tests.ts @@ -0,0 +1,101 @@ +function dwtOnReady() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer' + if (DWObject) { + let count = DWObject.SourceCount; + if (count === 0) { + DWObject.CloseSourceManager(); + DWObject.ImageCaptureDriverType = 0; + DWObject.OpenSourceManager(); + count = DWObject.SourceCount; + } + } +} + +function acquireImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.SelectSourceByIndex(0); // Use method SelectSourceByIndex to avoid the 'Select Source' dialog + DWObject.OpenSource(); + DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan. + DWObject.AcquireImage({}, () => {}, (errorCode: number, errorString: string) => {DWObject.CloseSource(); }); + } +} + +function registerEvent() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + // The event OnPostTransfer fires after each image is scanned and transferred + DWObject.RegisterEvent("OnPostTransfer", function () {}); + + // The event OnPostLoad fires after the images from a local directory have been loaded into the control + DWObject.RegisterEvent("OnPostLoad", function () {}); + + // The event OnMouseClick fires when the mouse clicks on an image on Dynamic Web TWAIN viewer + DWObject.RegisterEvent("OnMouseClick", function () {}); + + // The event OnTopImageInTheViewChanged fires when the top image currently displayed in the viewer changes + DWObject.RegisterEvent("OnTopImageInTheViewChanged", function (index: number) { + DWObject.CurrentImageIndexInBuffer = index; + }); + } +} + +function editImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.RotateLeft(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.RotateRight(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.Mirror(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.Flip(DWObject.CurrentImageIndexInBuffer); + } +} + +function showImageEditor() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.ShowImageEditor(); + } +} + +function saveImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.ConvertToGrayScale(DWObject.CurrentImageIndexInBuffer); + DWObject.SaveAsJPEG("DynamicWebTWAIN.jpg", DWObject.CurrentImageIndexInBuffer); + DWObject.SaveAllAsMultiPageTIFF("DynamicWebTWAIN.tiff", () => {}, (errorCode: number, errorString: string) => {}); + DWObject.SaveAllAsPDF("DynamicWebTWAIN.pdf", () => {}, (errorCode: number, errorString: string) => {}); + } +} + +function updateLargeViewer() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + let DWObjectLargeViewer = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainerLargeViewer'); + if (DWObject) { + DWObject.CopyToClipboard(DWObject.CurrentImageIndexInBuffer); // Copy the current image in the thumbnail to clipboard in DIB format. + DWObjectLargeViewer.LoadDibFromClipboard(); // Load the image from Clipboard into the large viewer. + } +} + +function uploadImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.HTTPPort = 80; + DWObject.IfSSL = false; + DWObject.HTTPUploadThroughPost("www.dynamsoft.com", DWObject.CurrentImageIndexInBuffer, "upload", "tmp.jpg", () => {}, (errorCode: number, errorString: string) => {}); + } +} + +function downloadImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.HTTPPort = 80; + DWObject.HTTPDownload("www.dynamsoft.com", "img.png", () => {}, (errorCode: number, errorString: string) => {}); + } +} diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts new file mode 100644 index 0000000000..460158afe1 --- /dev/null +++ b/types/dwt/index.d.ts @@ -0,0 +1,3459 @@ +// Type definitions for dwt 12.3 +// Project: http://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx +// Definitions by: Xiao Ling +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/*! +* Dynamsoft WebTwain JavaScript Intellisense +* Product: Dynamsoft Web Twain +* Web Site: http://www.dynamsoft.com +* +* Copyright 2017, Dynamsoft Corporation +* Author: Dynamsoft Support Team +* Version: 12.3 +*/ + +/** + * @namespace Dynamsoft + */ +declare namespace Dynamsoft { + namespace WebTwainEnv { + function GetWebTwain (cid: string): WebTwain; + function RegisterEvent(event: string, fn: () => void): void; + } +} + +/** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ +declare enum EnumDWT_PixelType { + TWPT_BW = 0, + TWPT_GRAY = 1, + TWPT_RGB = 2, + TWPT_PALLETE = 3, + TWPT_CMY = 4, + TWPT_CMYK = 5, + TWPT_YUV = 6, + TWPT_YUVK = 7, + TWPT_CIEXYZ = 8, + TWPT_LAB = 9, + TWPT_SRGB = 10, + TWPT_SCRGB = 11, + TWPT_INFRARED = 16 +} + +declare enum EnumDWT_BorderStyle { + /** No border. */ + TWBS_NONE = 0, + /** Flat border. */ + TWBS_SINGLEFLAT = 1, + /** 3D border. */ + TWBS_SINGLE3D = 2 +} + +/** For query the operation that are supported by the data source on a capability . + * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT + */ +declare enum EnumDWT_MessageType { + TWQC_GET = 1, + TWQC_SET = 2, + TWQC_GETDEFAULT = 4, + TWQC_GETCURRENT = 8, + TWQC_RESET = 16 +} + +/** Capabilities */ +declare enum EnumDWT_Cap { + /** Nothing. */ + CAP_NONE = 0, + /** The application is willing to accept this number of images. */ + CAP_XFERCOUNT = 1, + /** Allows the application and Source to identify which compression schemes they have in + * common for Buffered Memory and File transfers. + * Note for File transfers: + * Since only certain file formats support compression, this capability must be negotiated after + * setting the desired file format with ICAP_IMAGEFILEFORMAT. + */ + ICAP_COMPRESSION = 256, + /** The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.). */ + ICAP_PIXELTYPE = 257, + /** Unless a quantity is dimensionless or uses a specified unit of measure, ICAP_UNITS determines + * the unit of measure for all quantities. + */ + ICAP_UNITS = 258, + /** Allows the application and Source to identify which transfer mechanisms the source supports. */ + ICAP_XFERMECH = 259, + /** The name or other identifying information about the Author of the image. It may include a copyright string. */ + CAP_AUTHOR = 4096, + /** A general note about the acquired image. */ + CAP_CAPTION = 4097, + /** If TRUE, Source must acquire data from the document feeder acquire area and other feeder + * capabilities can be used. If FALSE, Source must acquire data from the non-feeder acquire area + * and no other feeder capabilities can be used. + */ + CAP_FEEDERENABLED = 4098, + /** Reflect whether there are documents loaded in the Source's feeder. */ + CAP_FEEDERLOADED = 4099, + /** The date and time the image was acquired. + * Stored in the form "YYYY/MM/DD HH:mm:SS.sss" where YYYY is the year, MM is the + * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, + * and sss is the millisecond. + */ + CAP_TIMEDATE = 4100, + /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate + * which capabilities the Source will allow to be set by the application. Some capabilities can only + * be set if certain setup work has been done so the Source cannot globally answer which + * capabilities are "set-able." + */ + CAP_SUPPORTEDCAPS = 4101, + /** Allows the application and Source to negotiate capabilities to be used in States 5 and 6. */ + CAP_EXTENDEDCAPS = 4102, + /** If TRUE, the Source will automatically feed the next page from the document feeder after the + * number of frames negotiated for capture from each page are acquired. CAP_FEEDERENABLED + * must be TRUE to use this capability. + */ + CAP_AUTOFEED = 4103, + /** If TRUE, the Source will eject the current page being acquired from and will leave the feeder + * acquire area empty. + * If CAP_AUTOFEED is TRUE, a fresh page will be advanced. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_CLEARPAGE = 4104, + /** If TRUE, the Source will eject the current page and advance the next page in the document feeder + * into the feeder acquire area. + * If CAP_AUTOFEED is TRUE, the same action just described will occur and CAP_AUTOFEED will + * remain active. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_FEEDPAGE = 4105, + /** If TRUE, the Source will return the current page to the input side of the document feeder and + * feed the last page from the output side of the feeder back into the acquisition area. + * If CAP_AUTOFEED is TRUE, automatic feeding will continue after all negotiated frames from this + * page are acquired. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_REWINDPAGE = 4106, + /** If TRUE, the Source will display a progress indicator during acquisition and transfer, regardless + * of whether the Source's user interface is active. If FALSE, the progress indicator will be + * suppressed if the Source's user interface is inactive. + * The Source will continue to display device-specific instructions and error messages even with + * the Source user interface and progress indicators turned off. + */ + CAP_INDICATORS = 4107, + /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate + * which capabilities the Source will allow to be set by the application. Some capabilities can only + * be set if certain setup work has been done so the Source cannot globally answer which + * capabilities are "set-able." + */ + CAP_SUPPORTEDCAPSEXT = 4108, + /** This capability determines whether the device has a paper sensor that can detect documents on the ADF or Flatbed. */ + CAP_PAPERDETECTABLE = 4109, + /** If TRUE, indicates that this Source supports acquisition with the UI disabled; i.e., + * TW_USERINTERFACE's ShowUI field can be set to FALSE. If FALSE, indicates that this Source + * can only support acquisition with the UI enabled. + */ + CAP_UICONTROLLABLE = 4110, + /** If TRUE, the physical hardware (e.g., scanner, digital camera, image database, etc.) that + * represents the image source is attached, powered on, and communicating. + */ + CAP_DEVICEONLINE = 4111, + /** This capability is intended to boost the performance of a Source. The fundamental assumption + * behind AutoScan is that the device is able to capture the number of images indicated by the + * value of CAP_XFERCOUNT without waiting for the Application to request the image transfers. + * This is only possible if the device has internal buffers capable of caching the images it captures. + * The default behavior is undefined, because some high volume devices are incapable of anything + * but CAP_AUTOSCAN being equal to TRUE. However, if a Source supports FALSE, it should use it + * as the mandatory default, since this best describes the behavior of pre-1.8 TWAIN Applications. + */ + CAP_AUTOSCAN = 4112, + /** Allows an application to request the delivery of thumbnail representations for the set of images + * that are to be delivered. + * Setting CAP_THUMBNAILSENABLED to TRUE turns on thumbnail mode. Images transferred + * thereafter will be sent at thumbnail size (exact thumbnail size is determined by the Data Source). + * Setting this capability to FALSE turns thumbnail mode off and returns full size images. + */ + CAP_THUMBNAILSENABLED = 4113, + /** This indicates whether the scanner supports duplex. If so, it further indicates whether one-path + * or two-path duplex is supported. + */ + CAP_DUPLEX = 4114, + /** The user can set the duplex option to be TRUE or FALSE. If TRUE, the scanner scans both sides + * of a paper; otherwise, the scanner will scan only one side of the image. + */ + CAP_DUPLEXENABLED = 4115, + /** Allows an application to query a source to see if it implements the new user interface settings dialog. */ + CAP_ENABLEDSUIONLY = 4116, + CAP_CUSTOMDSDATA = 4117, + /** Allows the application to specify the starting endorser / imprinter number. All other endorser/ + * imprinter properties should be handled through the data source's user interface. + * The user can set the starting number for the endorser. + */ + CAP_ENDORSER = 4118, + /** Turns specific audible alarms on and off. */ + CAP_ALARMS = 4120, + /** The volume of a device's audible alarm. Note that this control affects the volume of all alarms; + * no specific volume control for individual types of alarms is provided. + */ + CAP_ALARMVOLUME = 4121, + /** The number of images to automatically capture. This does not refer to the number of images to + * be sent to the Application, use CAP_XFERCOUNT for that. + */ + CAP_AUTOMATICCAPTURE = 4122, + /** For automatic capture, this value selects the number of milliseconds before the first picture is to + * be taken, or the first image is to be scanned. + */ + CAP_TIMEBEFOREFIRSTCAPTURE = 4123, + /** For automatic capture, this value selects the milliseconds to wait between pictures taken, or images scanned. */ + CAP_TIMEBETWEENCAPTURES = 4124, + /** CapGet() reports the presence of data in the scanner's buffers. CapSet() with a value of TWCB_CLEAR immediately clears the buffers. */ + CAP_CLEARBUFFERS = 4125, + /** Describes the number of pages that the scanner can buffer when CAP_AUTOSCAN is enabled. */ + CAP_MAXBATCHBUFFERS = 4126, + /** The date and time of the device's clock. + * Managed in the form "YYYY/MM/DD HH:mm:SS:sss" where YYYY is the year, MM is the + * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, + * and sss is the millisecond. + */ + CAP_DEVICETIMEDATE = 4127, + /** CapGet() reports the kinds of power available to the device. CapGetCurrent() reports the current power supply in use. */ + CAP_POWERSUPPLY = 4128, + /** This capability queries the Source for UI support for preview mode. If TRUE, the Source supports preview UI. */ + CAP_CAMERAPREVIEWUI = 4129, + /** A string containing the serial number of the currently selected device in the Source. Multiple + * devices may all report the same serial number. + */ + CAP_SERIALNUMBER = 4132, + /** CapGet() returns the current list of available printer devices, along with the one currently being used for negotiation. + * CapSet() selects the current device for negotiation, and optionally constrains the list. + * Top/Bottom refers to duplex devices, and indicates if the printer is writing on the top or the bottom of the sheet of paper. + * Simplex devices use the top settings. Before/After indicates whether printing occurs before or after the sheet of paper has been scanned. + */ + CAP_PRINTER = 4134, + /** Turns the current CAP_PRINTER device on or off. */ + CAP_PRINTERENABLED = 4135, + /** The User can set the starting number for the current CAP_PRINTER device. */ + CAP_PRINTERINDEX = 4136, + /** Specifies the appropriate current CAP_PRINTER device mode. + * Note: + * • TWPM_SINGLESTRING specifies that the printed text will consist of a single string. + * • TWPM _MULTISTRING specifies that the printed text will consist of an enumerated list of + * strings to be printed in order. + * • TWPM _COMPOUNDSTRING specifies that the printed string will consist of a compound of a + * String followed by a value followed by a suffix string. + */ + CAP_PRINTERMODE = 4137, + /** Specifies the string(s) that are to be used in the string component when the current + * CAP_PRINTER device is enabled. + */ + CAP_PRINTERSTRING = 4138, + /** Specifies the string that shall be used as the current CAP_PRINTER device's suffix. */ + CAP_PRINTERSUFFIX = 4139, + /** Allows Application and Source to identify which languages they have in common for the exchange of string data, + * and to select the language of the internal UI. Since the TWLG_xxxx codes include language and country data, there is no separate + * capability for selecting the country. + */ + CAP_LANGUAGE = 4140, + /** Helps the Application determine any special actions it may need to take when negotiating + * frames with the Source. Allowed values are listed in . + * TWFA_NONE: The alignment is free-floating. Applications should assume + * that the origin for frames is on the left. + * TWFA_LEFT: The alignment is to the left. + * TWFA_CENTER: The alignment is centered. This means that the paper will + * be fed in the middle of the ICAP_PHYSICALWIDTH of the + * device. If this is set, then the Application should calculate + * any frames with a left offset of zero. + * TWFA_RIGHT: The alignment is to the right. + */ + CAP_FEEDERALIGNMENT = 4141, + /** TWFO_FIRSTPAGEFIRST if the feeder starts with the top of the first page. + * TWFO_LASTPAGEFIRST is the feeder starts with the top of the last page. + */ + CAP_FEEDERORDER = 4142, + /** Indicates whether the physical hardware (e.g. scanner, digital camera) is capable of acquiring + * multiple images of the same page without changes to the physical registration of that page. + */ + CAP_REACQUIREALLOWED = 4144, + /** The minutes of battery power remaining to the device. */ + CAP_BATTERYMINUTES = 4146, + /** When used with CapGet(), return the percentage of battery power level on camera. If -1 is returned, it indicates that the battery is not present. */ + CAP_BATTERYPERCENTAGE = 4147, + /** Added 1.91 */ + CAP_CAMERASIDE = 4148, + /** Added 1.91 */ + CAP_SEGMENTED = 4149, + /** Added 2.0 */ + CAP_CAMERAENABLED = 4150, + /** Added 2.0 */ + CAP_CAMERAORDER = 4151, + /** Added 2.0 */ + CAP_MICRENABLED = 4152, + /** Added 2.0 */ + CAP_FEEDERPREP = 4153, + /** Added 2.0 */ + CAP_FEEDERPOCKET = 4154, + /** Added 2.1 */ + CAP_AUTOMATICSENSEMEDIUM = 4155, + /** Added 2.1 */ + CAP_CUSTOMINTERFACEGUID = 4156, + /** TRUE enables and FALSE disables the Source's Auto-brightness function (if any). */ + ICAP_AUTOBRIGHT = 4352, + /** The brightness values available within the Source. */ + ICAP_BRIGHTNESS = 4353, + /** The contrast values available within the Source. */ + ICAP_CONTRAST = 4355, + /** Specifies the square-cell halftone (dithering) matrix the Source should use to halftone the image. */ + ICAP_CUSTHALFTONE = 4356, + /** Specifies the exposure time used to capture the image, in seconds. */ + ICAP_EXPOSURETIME = 4357, + /** Describes the color characteristic of the subtractive filter applied to the image data. Multiple + * filters may be applied to a single acquisition. + */ + ICAP_FILTER = 4358, + /** Specifies whether or not the image was acquired using a flash. */ + ICAP_FLASHUSED = 4359, + /** Gamma correction value for the image data. */ + ICAP_GAMMA = 4360, + /** A list of names of the halftone patterns available within the Source. */ + ICAP_HALFTONES = 4361, + /** Specifies which value in an image should be interpreted as the lightest "highlight." All values + * "lighter" than this value will be clipped to this value. Whether lighter values are smaller or + * larger can be determined by examining the Current value of ICAP_PIXELFLAVOR. + */ + ICAP_HIGHLIGHT = 4362, + /** Informs the application which file formats the Source can generate (CapGet()). Tells the Source which file formats the application can handle (CapSet()). + * TWFF_TIFF Used for document + * TWFF_PICT Native Macintosh + * TWFF_BMP Native Microsoft + * TWFF_XBM Used for document + * TWFF_JFIF Wrapper for JPEG + * TWFF_FPX FlashPix, used with digital + * TWFF_TIFFMULTI Multi-page TIFF files + * TWFF_PNG An image format standard intended for use on the web, replaces GIF + * TWFF_SPIFF A standard from JPEG, intended to replace JFIF, also supports JBIG + * TWFF_EXIF File format for use with digital cameras. + */ + ICAP_IMAGEFILEFORMAT = 4364, + /** TRUE means the lamp is currently, or should be set to ON. Sources may not support CapSet() operations. */ + ICAP_LAMPSTATE = 4365, + /** Describes the general color characteristic of the light source used to acquire the image. */ + ICAP_LIGHTSOURCE = 4366, + /** Defines which edge of the "paper" the image's "top" is aligned with. This information is used to adjust the frames to match the + * scanning orientation of the paper. For instance, if an ICAP_SUPPORTEDSIZE of TWSS_ISOA4 has been negotiated, + * and ICAP_ORIENTATION is set to TWOR_LANDSCAPE, then the Source must rotate the frame it downloads to the scanner to reflect the + * orientation of the paper. Please note that setting ICAP_ORIENTATION does not affect the values reported by ICAP_FRAMES; + * it just causes the Source to use them in a different way. The upper-left of the image is defined as the location where both the primary and + * secondary scans originate. (The X axis is the primary scan direction and the Y axis is the secondary scan direction.) + * For a flatbed scanner, the light bar moves in the secondary scan direction. For a handheld scanner, the scanner is drug in the + * secondary scan direction. For a digital camera, the secondary direction is the vertical axis when the viewed image is considered upright. + */ + ICAP_ORIENTATION = 4368, + /** The maximum physical width (X-axis) the Source can acquire (measured in units of ICAP_UNITS). */ + ICAP_PHYSICALWIDTH = 4369, + /** The maximum physical height (Y-axis) the Source can acquire (measured in units of ICAP_UNITS). */ + ICAP_PHYSICALHEIGHT = 4370, + /** Specifies which value in an image should be interpreted as the darkest "shadow." All values + * "darker" than this value will be clipped to this value. + */ + ICAP_SHADOW = 4371, + /** The list of frames the Source will acquire on each page. */ + ICAP_FRAMES = 4372, + /** The native optical resolution along the X-axis of the device being controlled by the Source. Most + * devices will respond with a single value (TW_ONEVALUE). + * This is NOT a list of all resolutions that can be generated by the device. Rather, this is the + * resolution of the device's optics. Measured in units of pixels per unit as defined by + * ICAP_UNITS (pixels per TWUN_PIXELS yields dimensionless data). + */ + ICAP_XNATIVERESOLUTION = 4374, + /** The native optical resolution along the Y-axis of the device being controlled by the Source. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). + */ + ICAP_YNATIVERESOLUTION = 4375, + /** All the X-axis resolutions the Source can provide. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). That is, when the units are TWUN_PIXELS, both + * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources + * like to report the actual number of pixels that the device reports, but that response is more + * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. + */ + ICAP_XRESOLUTION = 4376, + /** All the Y-axis resolutions the Source can provide. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). That is, when the units are TWUN_PIXELS, both + * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources + * like to report the actual number of pixels that the device reports, but that response is more + * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. + */ + ICAP_YRESOLUTION = 4377, + /** The maximum number of frames the Source can provide or the application can accept per page. + * This is a bounding capability only. It does not establish current or future behavior. + */ + ICAP_MAXFRAMES = 4378, + /** This is used with buffered memory transfers. If TRUE, Source can provide application with tiled image data. */ + ICAP_TILES = 4379, + /** Specifies how the bytes in an image are filled by the Source. TWBO_MSBFIRST indicates that the leftmost bit in the byte (usually bit 7) is + * the byte's Most Significant Bit. + */ + ICAP_BITORDER = 4380, + /** Used for CCITT Group 3 2-dimensional compression. The 'K' factor indicates how often the + * new compression baseline should be re-established. A value of 2 or 4 is common in facsimile + * communication. A value of zero in this field will indicate an infinite K factor—the baseline is + * only calculated at the beginning of the transfer. + */ + ICAP_CCITTKFACTOR = 4381, + /** Describes whether the image was captured transmissively or reflectively. */ + ICAP_LIGHTPATH = 4382, + /** Sense of the pixel whose numeric value is zero (minimum data value). */ + ICAP_PIXELFLAVOR = 4383, + /** Allows the application and Source to identify which color data formats are available. There are + * two options, "planar" and "chunky." + */ + ICAP_PLANARCHUNKY = 4384, + /** How the Source can/should rotate the scanned image data prior to transfer. This doesn't use + * ICAP_UNITS. It is always measured in degrees. Any applied value is additive with any + * rotation specified in ICAP_ORIENTATION. + */ + ICAP_ROTATION = 4385, + /** For devices that support fixed frame sizes. + * Defined sizes match typical page sizes. This specifies the size(s) the Source can/should use to acquire image data. + */ + ICAP_SUPPORTEDSIZES = 4386, + /** Specifies the dividing line between black and white. This is the value the Source will use to + * threshold, if needed, when ICAP_PIXELTYPE:TWPT_BW. + * The value is normalized so there are no units of measure associated with this ICAP. + */ + ICAP_THRESHOLD = 4387, + /** All the X-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. */ + ICAP_XSCALING = 4388, + /** All the Y-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. + * There are no units inherent with this data as it is normalized to 1.0 being "unscaled." + */ + ICAP_YSCALING = 4389, + /** Used for CCITT data compression only. Indicates the bit order representation of the stored compressed codes. */ + ICAP_BITORDERCODES = 4390, + /** Used only for CCITT data compression. Specifies whether the compressed codes' pixel "sense" + * will be inverted from the Current value of ICAP_PIXELFLAVOR prior to transfer. + */ + ICAP_PIXELFLAVORCODES = 4391, + /** Allows the application and Source to agree upon a common set of color descriptors that are + * made available by the Source. This ICAP is only useful for JPEG-compressed buffered memory image transfers. + */ + ICAP_JPEGPIXELTYPE = 4392, + /** Used only with CCITT data compression. Specifies the minimum number of words of compressed codes (compressed data) to be transmitted per line. */ + ICAP_TIMEFILL = 4394, + /** Specifies the pixel bit depths for the Current value of ICAP_PIXELTYPE. For example, when + * using ICAP_PIXELTYPE:TWPT_GRAY, this capability specifies whether this is 8-bit gray or 4-bit gray. + * This depth applies to all the data channels (for instance, the R, G, and B channels will all have + * this same bit depth for RGB data). + */ + ICAP_BITDEPTH = 4395, + /** Specifies the Reduction Method the Source should use to reduce the bit depth of the data. Most + * commonly used with ICAP_PIXELTYPE:TWPT_BW to reduce gray data to black and white. + */ + ICAP_BITDEPTHREDUCTION = 4396, + /** If TRUE the Source will issue a MSG_XFERREADY before starting the scan. + * Note: The Source may need to scan the image before initiating the transfer. This is the case if + * the scanned image is rotated or merged with another scanned image. + */ + ICAP_UNDEFINEDIMAGESIZE = 4397, + /** Allows the application to query the data source to see if it supports extended image attribute capabilities, + * such as Barcode Recognition, Shaded Area Detection and Removal, Skew detection and Removal, and so on. + */ + ICAP_EXTIMAGEINFO = 4399, + /** Allows the source to define the minimum height (Y-axis) that the source can acquire. */ + ICAP_MINIMUMHEIGHT = 4400, + /** Allows the source to define theminimum width (X-axis) that the source can acquire. */ + ICAP_MINIMUMWIDTH = 4401, + /** Use this capability to have the Source discard blank images. The Application never sees these + * images during the scanning session. + * TWBP_DISABLE – this must be the default state for the Source. It indicates that all images will + * be delivered to the Application, none of them will be discarded. + * TWBP_AUTO – if this is used, then the Source will decide if an image is blank or not and discard + * as appropriate. + * If the specified value is a positive number in the range 0 to 231–1, then this capability will use it + * as the byte size cutoff point to identify which images are to be discarded. If the size of the image + * is less than or equal to this value, then it will be discarded. If the size of the image is greater + * than this value, then it will be kept so that it can be transferred to the Application. + */ + ICAP_AUTODISCARDBLANKPAGES = 4404, + /** Flip rotation is used to properly orient images that flip orientation every other image. + * TWFR_BOOK The images to be scanned are viewed in book form, flipping each page from left to right or right to left. + * TWFR_FANFOLD The images to be scanned are viewed in fanfold paper style, flipping each page up or down. + */ + ICAP_FLIPROTATION = 4406, + /** Turns bar code detection on and off. */ + ICAP_BARCODEDETECTIONENABLED = 4407, + /** Provides a list of bar code types that can be detected by the current Data Source. */ + ICAP_SUPPORTEDBARCODETYPES = 4408, + /** The maximum number of supported search priorities. */ + ICAP_BARCODEMAXSEARCHPRIORITIES = 4409, + /** A prioritized list of bar code types dictating the order in which bar codes will be sought. */ + ICAP_BARCODESEARCHPRIORITIES = 4410, + /** Restricts bar code searching to certain orientations, or prioritizes one orientation over the other. */ + ICAP_BARCODESEARCHMODE = 4411, + /** Restricts the number of times a search will be retried if none are found on each page. */ + ICAP_BARCODEMAXRETRIES = 4412, + /** Restricts the total time spent on searching for a bar code on each page. */ + ICAP_BARCODETIMEOUT = 4413, + /** When used with CapGet(), returns all camera supported lens zooming range. */ + ICAP_ZOOMFACTOR = 4414, + /** Turns patch code detection on and off. */ + ICAP_PATCHCODEDETECTIONENABLED = 4415, + /** A list of patch code types that may be detected by the current Data Source. */ + ICAP_SUPPORTEDPATCHCODETYPES = 4416, + /** The maximum number of supported search priorities. */ + ICAP_PATCHCODEMAXSEARCHPRIORITIES = 4417, + /** A prioritized list of patch code types dictating the order in which patch codes will be sought. */ + ICAP_PATCHCODESEARCHPRIORITIES = 4418, + /** Restricts patch code searching to certain orientations, or prioritizes one orientation over the other. */ + ICAP_PATCHCODESEARCHMODE = 4419, + /** Restricts the number of times a search will be retried if none are found on each page. */ + ICAP_PATCHCODEMAXRETRIES = 4420, + /** Restricts the total time spent on searching for a patch code on each page. */ + ICAP_PATCHCODETIMEOUT = 4421, + /** For devices that support flash. CapSet() selects the flash to be used (if any). CapGet() reports the current setting. + * This capability replaces ICAP_FLASHUSED, which is only able to negotiate the flash being on or off. + */ + ICAP_FLASHUSED2 = 4422, + /** For devices that support image enhancement filtering. This capability selects the algorithm used to improve the quality of the image. */ + ICAP_IMAGEFILTER = 4423, + /** For devices that support noise filtering. This capability selects the algorithm used to remove noise. */ + ICAP_NOISEFILTER = 4424, + /** Overscan is used to scan outside of the boundaries described by ICAP_FRAMES, and is used to help acquire image data that + * may be lost because of skewing. + * This is primarily of use for transport scanners which rely on edge detection to begin scanning. + * If overscan is supported, then the device is capable of scanning in the inter-document gap to get the skewed image information. + */ + ICAP_OVERSCAN = 4425, + /** Turns automatic border detection on and off. */ + ICAP_AUTOMATICBORDERDETECTION = 4432, + /** Turns automatic deskew correction on and off. */ + ICAP_AUTOMATICDESKEW = 4433, + /** When TRUE this capability depends on intelligent features within the Source to automatically + * rotate the image to the correct position. + */ + ICAP_AUTOMATICROTATE = 4434, + /** Added 1.9 */ + ICAP_JPEGQUALITY = 4435, + /** Added 1.91 */ + ICAP_FEEDERTYPE = 4436, + /** Added 1.91 */ + ICAP_ICCPROFILE = 4437, + /** Added 2.0 */ + ICAP_AUTOSIZE = 4438, + /** Added 2.1 */ + ICAP_AUTOMATICCROPUSESFRAME = 4439, + /** Added 2.1 */ + ICAP_AUTOMATICLENGTHDETECTION = 4440, + /** Added 2.1 */ + ICAP_AUTOMATICCOLORENABLED = 4441, + /** Added 2.1 */ + ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE = 4442, + /** Added 2.1 */ + ICAP_COLORMANAGEMENTENABLED = 4443, + /** Added 2.1 */ + ICAP_IMAGEMERGE = 4444, + /** Added 2.1 */ + ICAP_IMAGEMERGEHEIGHTTHRESHOLD = 4445, + /** Added 2.1 */ + ICAP_SUPPORTEDEXTIMAGEINFO = 4446 +} + +/** Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. + * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = + * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. + */ +declare enum EnumDWT_CapType { + /** Nothing. */ + TWON_NONE = 0, + /** A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and + * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS + * capability, would use this type of container. + */ + TWON_ARRAY = 3, + /** This is the most general type because it defines a list of values from which the Current Value can be chosen. + * The values do not progress uniformly through a range and there is not a consistent step size between the values. + * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). + */ + TWON_ENUMERATION = 4, + /** A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. + * For example, a capability that indicates the presence of a document feeder could be of this type. + */ + TWON_ONEVALUE = 5, + /** Many capabilities allow users to select their current value from a range of regularly spaced values. + * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. + * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). + */ + TWON_RANGE = 6 +} + +/** ICAP_XFERMECH values. */ +declare enum EnumDWT_TransferMode { + /** Native transfers require the data to be transferred to a single large block of RAM. Therefore, + * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. + */ + TWSX_NATIVE = 0, + /** Disk File Mode Transfers. */ + TWSX_FILE = 1, + /** Buffered Memory Mode Transfers. */ + TWSX_MEMORY = 2, + /** added 1.91 */ + TWSX_MEMFILE = 4 +} + +/** ICAP_IMAGEFILEFORMAT values. */ +declare enum EnumDWT_FileFormat { + /** Used for document imaging. Tagged Image File Format */ + TWFF_TIFF = 0, + /** Native Macintosh format. Macintosh PICT */ + TWFF_PICT = 1, + /** Native Microsoft format. Windows Bitmap */ + TWFF_BMP = 2, + /** Used for document imaging. X-Windows Bitmap */ + TWFF_XBM = 3, + /** Wrapper for JPEG images. JPEG File Interchange Format */ + TWFF_JFIF = 4, + /** FlashPix, used with digital cameras. Flash Pix */ + TWFF_FPX = 5, + /** Multi-page TIFF files. Multi-page tiff file */ + TWFF_TIFFMULTI = 6, + /** An image format standard intended for use on the web, replaces GIF. */ + TWFF_PNG = 7, + /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ + TWFF_SPIFF = 8, + /** File format for use with digital cameras. */ + TWFF_EXIF = 9, + /** A file format from Adobe. 1.91 NB: this is not PDF/A */ + TWFF_PDF = 10, + /** A file format from the Joint Photographic Experts Group. 1.91 */ + TWFF_JP2 = 11, + /** 1.91 */ + TWFF_JPN = 12, + /** 1.91 */ + TWFF_JPX = 13, + /** A file format from LizardTech. 1.91 */ + TWFF_DEJAVU = 14, + /** A file format from Adobe. 2.0 */ + TWFF_PDFA = 15, + /** 2.1 Adobe PDF/A, Version 2 */ + TWFF_PDFA2 = 16 +} + +/** TIFF file compression type. */ +declare enum EnumDWT_TIFFCompressionType { + /** Auto mode. */ + TIFF_AUTO = 0, + /** Dump mode. */ + TIFF_NONE = 1, + /** CCITT modified Huffman RLE. */ + TIFF_RLE = 2, + /** CCITT Group 3 fax encoding. */ + TIFF_FAX3 = 3, + /** CCITT T.4 (TIFF 6 name). */ + TIFF_T4 = 3, + /** CCITT Group 4 fax encoding */ + TIFF_FAX4 = 4, + /** CCITT T.6 (TIFF 6 name). */ + TIFF_T6 = 4, + /** Lempel Ziv and Welch */ + TIFF_LZW = 5, + TIFF_JPEG = 7, + TIFF_PACKBITS = 32773 +} + +/** The method to do interpolation. */ +declare enum EnumDWT_InterpolationMethod { + IM_NEARESTNEIGHBOUR = 1, + IM_BILINEAR = 2, + IM_BICUBIC = 3, + IM_BESTQUALITY = 5 +} + +/** Image type */ +declare enum EnumDWT_ImageType { + /** Native Microsoft format. */ + IT_BMP = 0, + /** JPEG format. */ + IT_JPG = 1, + /** Tagged Image File Format. */ + IT_TIF = 2, + /** An image format standard intended for use on the web, replaces GIF. */ + IT_PNG = 3, + /** A file format from Adobe. */ + IT_PDF = 4, + IT_ALL = 5 +} + +/** PDF file compression type. */ +declare enum EnumDWT_PDFCompressionType { + /** Auto mode. */ + PDF_AUTO = 0, + /** CCITT Group 3 fax encoding. */ + PDF_FAX3 = 1, + /** CCITT Group 4 fax encoding */ + PDF_FAX4 = 2, + /** Lempel Ziv and Welch */ + PDF_LZW = 3, + /** CCITT modified Huffman RLE. */ + PDF_RLE = 4, + PDF_JPEG = 5 +} + +declare enum EnumDWT_ShowMode { + /** Activates the window and displays it in its current size and position. */ + SW_ACTIVE = 0, + /** Maximizes the window */ + SW_MAX = 1, + /** Minimize the window */ + SW_MIN = 2, + /** Close the latest opened editor window */ + SW_CLOSE = 3, + /** Check whether a window exists */ + SW_IFLIVE = 4 +} + +/** The kind of data stored in the container. */ +declare enum EnumDWT_CapValueType { + TWTY_INT8 = 0, + /** Means Item is a TW_INT16 */ + TWTY_INT16 = 1, + /** Means Item is a TW_INT32 */ + TWTY_INT32 = 2, + /** Means Item is a TW_UINT8 */ + TWTY_UINT8 = 3, + /** Means Item is a TW_UINT16 */ + TWTY_UINT16 = 4, + /** Means Item is a TW_int */ + TWTY_int = 5, + /** Means Item is a TW_BOOL */ + TWTY_BOOL = 6, + /** Means Item is a TW_FIX32 */ + TWTY_FIX32 = 7, + /** Means Item is a TW_FRAME */ + TWTY_FRAME = 8, + /** Means Item is a TW_STR32 */ + TWTY_STR32 = 9, + /** Means Item is a TW_STR64 */ + TWTY_STR64 = 10, + /** Means Item is a TW_STR128 */ + TWTY_STR128 = 11, + /** Means Item is a TW_STR255 */ + TWTY_STR255 = 12 +} + +/** ICAP_UNITS values. */ +declare enum EnumDWT_UnitType { + TWUN_INCHES = 0, + TWUN_CENTIMETERS = 1, + TWUN_PICAS = 2, + TWUN_POINTS = 3, + TWUN_TWIPS = 4, + TWUN_PIXELS = 5, + TWUN_MILLIMETERS = 6 +} + +/** ICAP_DUPLEX values. */ +declare enum EnumDWT_DUPLEX { + TWDX_NONE = 0, + TWDX_1PASSDUPLEX = 1, + TWDX_2PASSDUPLEX = 2 +} + +/** CAP_LANGUAGE values. */ +declare enum EnumDWT_CapLanguage { + /** Danish */ + TWLG_DAN = 0, + /** Dutch */ + TWLG_DUT = 1, + /** International English */ + TWLG_ENG = 2, + /** French Canadian */ + TWLG_FCF = 3, + /** Finnish */ + TWLG_FIN = 4, + /** French */ + TWLG_FRN = 5, + /** German */ + TWLG_GER = 6, + /** Icelandic */ + TWLG_ICE = 7, + /** Italian */ + TWLG_ITN = 8, + /** Norwegian */ + TWLG_NOR = 9, + /** Portuguese */ + TWLG_POR = 10, + /** Spanish */ + TWLG_SPA = 11, + /** Swedish */ + TWLG_SWE = 12, + /** U.S. English */ + TWLG_USA = 13, + /** Added for 1.8 */ + TWLG_USERLOCALE = -1, + TWLG_AFRIKAANS = 14, + TWLG_ALBANIA = 15, + TWLG_ARABIC = 16, + TWLG_ARABIC_ALGERIA = 17, + TWLG_ARABIC_BAHRAIN = 18, + TWLG_ARABIC_EGYPT = 19, + TWLG_ARABIC_IRAQ = 20, + TWLG_ARABIC_JORDAN = 21, + TWLG_ARABIC_KUWAIT = 22, + TWLG_ARABIC_LEBANON = 23, + TWLG_ARABIC_LIBYA = 24, + TWLG_ARABIC_MOROCCO = 25, + TWLG_ARABIC_OMAN = 26, + TWLG_ARABIC_QATAR = 27, + TWLG_ARABIC_SAUDIARABIA = 28, + TWLG_ARABIC_SYRIA = 29, + TWLG_ARABIC_TUNISIA = 30, + /** United Arabic Emirates */ + TWLG_ARABIC_UAE = 31, + TWLG_ARABIC_YEMEN = 32, + TWLG_BASQUE = 33, + TWLG_BYELORUSSIAN = 34, + TWLG_BULGARIAN = 35, + TWLG_CATALAN = 36, + TWLG_CHINESE = 37, + TWLG_CHINESE_HONGKONG = 38, + /** People's Republic of China */ + TWLG_CHINESE_PRC = 39, + TWLG_CHINESE_SINGAPORE = 40, + TWLG_CHINESE_SIMPLIFIED = 41, + TWLG_CHINESE_TAIWAN = 42, + TWLG_CHINESE_TRADITIONAL = 43, + TWLG_CROATIA = 44, + TWLG_CZECH = 45, + TWLG_DANISH = 0, + TWLG_DUTCH = 1, + TWLG_DUTCH_BELGIAN = 46, + TWLG_ENGLISH = 2, + TWLG_ENGLISH_AUSTRALIAN = 47, + TWLG_ENGLISH_CANADIAN = 48, + TWLG_ENGLISH_IRELAND = 49, + TWLG_ENGLISH_NEWZEALAND = 50, + TWLG_ENGLISH_SOUTHAFRICA = 51, + TWLG_ENGLISH_UK = 52, + TWLG_ENGLISH_USA = 13, + TWLG_ESTONIAN = 53, + TWLG_FAEROESE = 54, + TWLG_FARSI = 55, + TWLG_FINNISH = 4, + TWLG_FRENCH = 5, + TWLG_FRENCH_BELGIAN = 56, + TWLG_FRENCH_CANADIAN = 3, + TWLG_FRENCH_LUXEMBOURG = 57, + TWLG_FRENCH_SWISS = 58, + TWLG_GERMAN = 6, + TWLG_GERMAN_AUSTRIAN = 59, + TWLG_GERMAN_LUXEMBOURG = 60, + TWLG_GERMAN_LIECHTENSTEIN = 61, + TWLG_GERMAN_SWISS = 62, + TWLG_GREEK = 63, + TWLG_HEBREW = 64, + TWLG_HUNGARIAN = 65, + TWLG_ICELANDIC = 7, + TWLG_INDONESIAN = 66, + TWLG_ITALIAN = 8, + TWLG_ITALIAN_SWISS = 67, + TWLG_JAPANESE = 68, + TWLG_KOREAN = 69, + TWLG_KOREAN_JOHAB = 70, + TWLG_LATVIAN = 71, + TWLG_LITHUANIAN = 72, + TWLG_NORWEGIAN = 9, + TWLG_NORWEGIAN_BOKMAL = 73, + TWLG_NORWEGIAN_NYNORSK = 74, + TWLG_POLISH = 75, + TWLG_PORTUGUESE = 10, + TWLG_PORTUGUESE_BRAZIL = 76, + TWLG_ROMANIAN = 77, + TWLG_RUSSIAN = 78, + TWLG_SERBIAN_LATIN = 79, + TWLG_SLOVAK = 80, + TWLG_SLOVENIAN = 81, + TWLG_SPANISH = 11, + TWLG_SPANISH_MEXICAN = 82, + TWLG_SPANISH_MODERN = 83, + TWLG_SWEDISH = 12, + TWLG_THAI = 84, + TWLG_TURKISH = 85, + TWLG_UKRANIAN = 86, + /** More stuff added for 1.8 */ + TWLG_ASSAMESE = 87, + TWLG_BENGALI = 88, + TWLG_BIHARI = 89, + TWLG_BODO = 90, + TWLG_DOGRI = 91, + TWLG_GUJARATI = 92, + TWLG_HARYANVI = 93, + TWLG_HINDI = 94, + TWLG_KANNADA = 95, + TWLG_KASHMIRI = 96, + TWLG_MALAYALAM = 97, + TWLG_MARATHI = 98, + TWLG_MARWARI = 99, + TWLG_MEGHALAYAN = 100, + TWLG_MIZO = 101, + TWLG_NAGA = 102, + TWLG_ORISSI = 103, + TWLG_PUNJABI = 104, + TWLG_PUSHTU = 105, + TWLG_SERBIAN_CYRILLIC = 106, + TWLG_SIKKIMI = 107, + TWLG_SWEDISH_FINLAND = 108, + TWLG_TAMIL = 109, + TWLG_TELUGU = 110, + TWLG_TRIPURI = 111, + TWLG_URDU = 112, + TWLG_VIETNAMESE = 113 +} + +/** TWAIN Supported sizes. */ +declare enum EnumDWT_CapSupportedSizes { + /** 0 */ + TWSS_NONE = 0, + /** 1 */ + TWSS_A4LETTER = 1, + /** 2 */ + TWSS_B5LETTER = 2, + /** 3 */ + TWSS_USLETTER = 3, + /** 4 */ + TWSS_USLEGAL = 4, + /** Added 1.5 + * 5 + */ + TWSS_A5 = 5, + /** 6 */ + TWSS_B4 = 6, + /** 7 */ + TWSS_B6 = 7, + /** Added 1.7 + * 9 + */ + TWSS_USLEDGER = 9, + /** 10 */ + TWSS_USEXECUTIVE = 10, + /** 11 */ + TWSS_A3 = 11, + /** 12 */ + TWSS_B3 = 12, + /** 13 */ + TWSS_A6 = 13, + /** 14 */ + TWSS_C4 = 14, + /** 15 */ + TWSS_C5 = 15, + /** 16 */ + TWSS_C6 = 16, + /** Added 1.8 + * 17 + */ + TWSS_4A0 = 17, + /** 18 */ + TWSS_2A0 = 18, + /** 19 */ + TWSS_A0 = 19, + /** 20 */ + TWSS_A1 = 20, + /** 21 */ + TWSS_A2 = 21, + /** 1 */ + TWSS_A4 = 1, + /** 22 */ + TWSS_A7 = 22, + /** 23 */ + TWSS_A8 = 23, + /** 24 */ + TWSS_A9 = 24, + /** 25 */ + TWSS_A10 = 25, + /** 26 */ + TWSS_ISOB0 = 26, + /** 27 */ + TWSS_ISOB1 = 27, + /** 28 */ + TWSS_ISOB2 = 28, + /** 12 */ + TWSS_ISOB3 = 12, + /** 6 */ + TWSS_ISOB4 = 6, + /** 29 */ + TWSS_ISOB5 = 29, + /** 7 */ + TWSS_ISOB6 = 7, + /** 30 */ + TWSS_ISOB7 = 30, + /** 31 */ + TWSS_ISOB8 = 31, + /** 32 */ + TWSS_ISOB9 = 32, + /** 33 */ + TWSS_ISOB10 = 33, + /** 34 */ + TWSS_JISB0 = 34, + /** 35 */ + TWSS_JISB1 = 35, + /** 36 */ + TWSS_JISB2 = 36, + /** 37 */ + TWSS_JISB3 = 37, + /** 38 */ + TWSS_JISB4 = 38, + /** 2 */ + TWSS_JISB5 = 2, + /** 39 */ + TWSS_JISB6 = 39, + /** 40 */ + TWSS_JISB7 = 40, + /** 41 */ + TWSS_JISB8 = 41, + /** 41 */ + TWSS_JISB9 = 42, + /** 43 */ + TWSS_JISB10 = 43, + /** 44 */ + TWSS_C0 = 44, + /** 45 */ + TWSS_C1 = 45, + /** 46 */ + TWSS_C2 = 46, + /** 47 */ + TWSS_C3 = 47, + /** 48 */ + TWSS_C7 = 48, + /** 49 */ + TWSS_C8 = 49, + /** 50 */ + TWSS_C9 = 50, + /** 51 */ + TWSS_C10 = 51, + /** 52 */ + TWSS_USSTATEMENT = 52, + /** 53 */ + TWSS_BUSINESSCARD = 53, + /** 54. Added 2.1 */ + TWSS_MAXSIZE = 54 +} + +/** CAP_FEEDERALIGNMENT values. */ +declare enum EnumDWT_CapFeederAlignment { + /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ + TWFA_NONE = 0, + /** The alignment is to the left. */ + TWFA_LEFT = 1, + /** The alignment is centered. This means that the paper will be fed in the middle of the ICAP_PHYSICALWIDTH of the + * device. If this is set, then the Application should calculate any frames with a left offset of zero. + */ + TWFA_CENTER = 2, + /** The alignment is to the right. */ + TWFA_RIGHT = 3 +} +/** CAP_FEEDERORDER values. */ +declare enum EnumDWT_CapFeederOrder { + /** The feeder starts with the top of the first page. */ + TWFO_FIRSTPAGEFIRST = 0, + /** The feeder starts with the top of the last page. */ + TWFO_LASTPAGEFIRST = 1 +} + +/** CAP_PRINTER values. */ +declare enum EnumDWT_CapPrinter { + TWPR_IMPRINTERTOPBEFORE = 0, + TWPR_IMPRINTERTOPAFTER = 1, + TWPR_IMPRINTERBOTTOMBEFORE = 2, + TWPR_IMPRINTERBOTTOMAFTER = 3, + TWPR_ENDORSERTOPBEFORE = 4, + TWPR_ENDORSERTOPAFTER = 5, + TWPR_ENDORSERBOTTOMBEFORE = 6, + TWPR_ENDORSERBOTTOMAFTER = 7 +} + +/** CAP_PRINTERMODE values. */ +declare enum EnumDWT_CapPrinterMode { + /** Specifies that the printed text will consist of a single string. */ + TWPM_SINGLESTRING = 0, + /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ + TWPM_MULTISTRING = 1, + /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ + TWPM_COMPOUNDSTRING = 2 +} + +/** ICAP_BITDEPTHREDUCTION values. */ +declare enum EnumDWT_CapBitdepthReduction { + TWBR_THRESHOLD = 0, + TWBR_HALFTONE = 1, + TWBR_CUSTHALFTONE = 2, + TWBR_DIFFUSION = 3 +} + +/** ICAP_BITORDER values. */ +declare enum EnumDWT_CapBitOrder { + TWBO_LSBFIRST = 0, + /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ + TWBO_MSBFIRST = 1 +} + +/** ICAP_FILTER values. */ +declare enum EnumDWT_CapFilterType { + TWFT_RED = 0, + TWFT_GREEN = 1, + TWFT_BLUE = 2, + TWFT_NONE = 3, + TWFT_WHITE = 4, + TWFT_CYAN = 5, + TWFT_MAGENTA = 6, + TWFT_YELLOW = 7, + TWFT_BLACK = 8 +} + +/** ICAP_FLASHUSED2 values. */ +declare enum EnumDWT_CapFlash { + TWFL_NONE = 0, + TWFL_OFF = 1, + TWFL_ON = 2, + TWFL_AUTO = 3, + TWFL_REDEYE = 4 +} + +/** ICAP_FLIPROTATION values. */ +declare enum EnumDWT_CapFlipRotation { + /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ + TWFR_BOOK = 0, + /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ + TWFR_FANFOLD = 1 +} + +/** ICAP_IMAGEFILTER values. */ +declare enum EnumDWT_CapImageFilter { + TWIF_NONE = 0, + TWIF_AUTO = 1, + /** Good for halftone images. */ + TWIF_LOWPASS = 2, + /** Good for improving text. */ + TWIF_BANDPASS = 3, + /** Good for improving fine lines. */ + TWIF_HIGHPASS = 4, + TWIF_TEXT = 3, + TWIF_FINELINE = 4 +} + +/** ICAP_LIGHTPATH values. */ +declare enum EnumDWT_CapLightPath { + TWLP_REFLECTIVE = 0, + TWLP_TRANSMISSIVE = 1 +} + +/** ICAP_LIGHTSOURCE values. */ +declare enum EnumDWT_CapLightSource { + TWLS_RED = 0, + TWLS_GREEN = 1, + TWLS_BLUE = 2, + TWLS_NONE = 3, + TWLS_WHITE = 4, + TWLS_UV = 5, + TWLS_IR = 6 +} + +/** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ +declare enum EnumDWT_MagType { + /** Added 2.0 */ + TWMD_MICR = 0, + /** added 2.1 */ + TWMD_RAW = 1, + /** added 2.1 */ + TWMD_INVALID = 2 +} + +/** ICAP_NOISEFILTER values. */ +declare enum EnumDWT_CapNoiseFilter { + TWNF_NONE = 0, + TWNF_AUTO = 1, + TWNF_LONEPIXEL = 2, + TWNF_MAJORITYRULE = 3 +} + +/** ICAP_ORIENTATION values. */ +declare enum EnumDWT_CapORientation { + TWOR_ROT0 = 0, + TWOR_ROT90 = 1, + TWOR_ROT180 = 2, + TWOR_ROT270 = 3, + TWOR_PORTRAIT = 0, + TWOR_LANDSCAPE = 3, + /** 2.0 */ + TWOR_AUTO = 4, + /** 2.0 */ + TWOR_AUTOTEXT = 5, + /** 2.0 */ + TWOR_AUTOPICTURE = 6 +} + +/** ICAP_OVERSCAN values. */ +declare enum EnumDWT_CapOverscan { + TWOV_NONE = 0, + TWOV_AUTO = 1, + TWOV_TOPBOTTOM = 2, + TWOV_LEFTRIGHT = 3, + TWOV_ALL = 4 +} + +/** ICAP_PIXELFLAVOR values. */ +declare enum EnumDWT_CapPixelFlavor { + /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ + TWPF_CHOCOLATE = 0, + /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ + TWPF_VANILLA = 1 +} + +/** ICAP_PLANARCHUNKY values. */ +declare enum EnumDWT_CapPlanarChunky { + TWPC_CHUNKY = 0, + TWPC_PLANAR = 1 +} + +/** Data source status. */ +declare enum EnumDWT_DataSourceStatus { + /** Indicate the data source is closed. */ + TWDSS_CLOSED = 0, + /** Indicate the data source is opened. */ + TWDSS_OPENED = 1, + /** Indicate the data source is enabled. */ + TWDSS_ENABLED = 2, + /** Indicate the data source is acquiring image. */ + TWDSS_ACQUIRING = 3 +} + +/** Fit window type */ +declare enum EnumDWT_FitWindowType { + /** Fit the image to the width and height of the window */ + enumFitWindow = 0, + /** Fit the image to the height of the window */ + enumFitWindowHeight = 1, + /** Fit the image to the width of the window */ + enumFitWindowWidth = 2 +} + +declare enum EnumDWT_UploadDataFormat { + Binary = 0, + Base64 = 1 +} + +declare enum EnumDWT_MouseShape { + Default = 0, + Hand = 1, + Crosshair = 2, + Zoom = 3 +} + +/** + * @class + */ +// properties (get/set) / sync functions +interface WebTwain { + /** + * Returns or sets whether multi-page selection is supported. + * @type {bool} + */ + AllowMultiSelect: boolean; + + /** + * [Deprecated.] Returns or sets whether allowing the plugin to send authentication request. The default value of this property is TRUE. + * @type {bool} + */ + AllowPluginAuthentication: boolean; + + /** + * [Deprecated.] Returns or sets whether the async mode is activated. With this mode, Dynamic Web TWAIN is able to upload/download files via HTTP/FTP asynchronously. The default value is false. + * @type {bool} + */ + AsyncMode: boolean; + + /** + * Returns or sets the background color of the main control. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + BackgroundColor: number; + + /** + * Returns or sets the fill color of the selected area of an image when it is cut, erased or rotated. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + BackgroundFillColor: number; + + /** + * [Deprecated.] Returns the number of barcode detected in an image. + * @type {int} + */ + BarcodeCount: number; + + /** + * Returns or sets the pixel bit depths for the current value of PixelType property. This is a runtime property. + * @type {short} + */ + BitDepth: number; + + /** + * Returns the current deviation of the pixels in the image. + * @type {float} + */ + BlankImageCurrentStdDev: number; + + /** + * Returns or sets the standard deviation of the pixels in the image. + * @type {float} + */ + BlankImageMaxStdDev: number; + + /** + * Returns or sets the dividing line between black and white. The default value is 128. + * @type {int} + */ + BlankImageThreshold: number; + + /** + * [Deprecated.] Returns or sets the border style. + * @type {EnumDWT_BorderStyle} + */ + BorderStyle: EnumDWT_BorderStyle; + + /** + * Returns or sets the brightness values available within the Source. This is a runtime property. + * @type {float} + */ + Brightness: number; + + /** + * [Deprecated.] Sets or returns whether brokerprocess is enabled for scanning. + * @type {int} + */ + BrokerProcessType: number; + + /** + * Sets or returns how much physical memory is allowed for storing images currently loaded in Dynamic Web TWAIN. Once the limit is reached, images will be cached on the hard disk. + * @type {int} + */ + BufferMemoryLimit: number; + + /** + * Specifies the capabiltiy to be negotiated. This is a runtime property. + * @type {EnumDWT_Cap} + */ + Capability: EnumDWT_Cap; + + /** + * Sets or returns the index (0-based) of a list to indicate the Current Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {int} + */ + CapCurrentIndex: number; + + /** + * Sets or returns the current value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapCurrentValue: number; + + /** + * Returns the index (0-based) of a list to indicate the Default Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime, read-only property. + * @type {int} + */ + CapDefaultIndex: number; + + /** + * Returns the default value in a range when the value of the CapType property is TWON_RANGE. This is a runtime, read-only property. + * @type {double} + */ + CapDefaultValue: number; + + /** + * Sets or returns the maximum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapMaxValue: number; + + /** + * Sets or returns the minimum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapMinValue: number; + + /** + * [Deprecated.] Sets or returns how many items are in the list when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. For String data type, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {int} + */ + CapNumItems: number; + + /** + * [Deprecated.] Replaced by GetCapItemsString method and SetCapItemsString method. + * @type {string} + */ + CapItemsString: string; + + /** + * Sets or returns the step size in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapStepSize: number; + + /** + * Sets or returns the type of capability container used to exchange capability information between application and source. This is a runtime property. + * @type {EnumDWT_CapType} + */ + CapType: EnumDWT_CapType; + + /** + * Returns or sets the value of the capability specified by Capability property when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {double} + */ + CapValue: number; + + /** + * Sets or returns the string value for a capability when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {string} + */ + CapValueString: string; + + /** + * Sets or returns the value type for reading the value of a capability. This is a runtime property. + * @type {short} + */ + CapValueType: number; + + /** + * Returns or sets the contrast values available within the Source. This is a runtime property. + * @type {float} + */ + Contrast: number; + + /** + * Sets or returns the product name string for the application identity. + * @type {string} + */ + ProductName: string; + + /** + * Returns or sets current index of image in buffer. This is a runtime property. + * @type {short} + */ + CurrentImageIndexInBuffer: number; + + /** + * Returns the device name of current source. This is a runtime, read-only property. + * @type {string} + */ + CurrentSourceName: string; + + /** + * Returns the value indicating the data source status. This is a runtime, read-only property. + * @type {int} + */ + DataSourceStatus: number; + + /** + * Returns the device name of default source. This is a runtime, read-only property. + * @type {string} + */ + DefaultSourceName: string; + + /** + * Returns whether the source supports duplex. If so, it further returns the level of duplex the Source supports (one pass or two pass duplex). This is a runtime, read-only property. + * @type {int} + */ + Duplex: number; + + /** + * [Deprecated.] Returns or sets whether the user can zoom image using hot key. + * @type {bool} + */ + EnableInteractiveZoom: boolean; + + /** + * Returns the error code. This is a runtime, read-only property. + * @type {int} + */ + ErrorCode: number; + + /** + * Returns the error string. This is a runtime, read-only property. + * @type {string} + */ + ErrorString: string; + + /** + * Returns or sets whether to resize the image to fit the image to the width or height of the window. To use the property, the view mode should be set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {EnumDWT_FitWindowType} + */ + FitWindowType: EnumDWT_FitWindowType; + + /** + * Returns or sets the password used to log into the FTP server. + * @type {string} + */ + FTPPassword: string; + + /** + * Returns or sets the port number of the FTP server. + * @type {int} + */ + FTPPort: number; + + /** + * Returns or sets the user name used to log into the FTP server. + * @type {string} + */ + FTPUserName: string; + + /** + * Returns how many images are in buffer. This is a runtime, read-only property. + * @type {short} + */ + HowManyImagesInBuffer: number; + + /** + * Specifies the field name of uploaded image through POST. + * @type {string} + */ + HttpFieldNameOfUploadedImage: string; + + /** + * [Deprecated.] Sets or returns the password used to log into the HTTP server. + * @type {string} + */ + HTTPPassword: string; + + /** + * Returns or sets the port number of the HTTP server. + * @type {int} + */ + HTTPPort: number; + + /** + * Returns the response string from the HTTP server if an error occurs for HTTPUploadThroughPost() method. This is a runtime, read-only property. + * @type {string} + */ + HTTPPostResponseString: string; + + /** + * [Deprecated.] Returns or sets the user name used to log into the HTTP server. + * @type {string} + */ + HTTPUserName: string; + + /** + * Returns or sets whether the feature of disk caching is enabled. + * @type {bool} + */ + IfAllowLocalCache: boolean; + + /** + * Returns or sets whether insert or append new scanned images. + * @type {bool} + */ + IfAppendImage: boolean; + + /** + * Returns or sets whether the Source's Auto-brightness function is enabled. This is a runtime property. + * @type {bool} + */ + IfAutoBright: boolean; + + /** + * Returns or sets whether the data source (scanner) will discard blank images during scanning. The property works only if the device and its driver support discarding blank pages. You can find whether your device supports this capbility from its user manual. Or, you can use the built-in methods of Dynamic Web TWAIN to detect blank images: IsBlankImage, IsBlankImageEx. + * @type {bool} + */ + IfAutoDiscardBlankpages: boolean; + + /** + * Returns or sets whether the Source enable automatic document feeding process. This is a runtime property. + * @type {bool} + */ + IfAutoFeed: boolean; + + /** + * Turns automatic border detection on and off. The property works only if the device and its driver support detecting the border automatically. You can find whether your device supports this capbility from its user manual. + * @type {bool} + */ + IfAutomaticBorderDetection: boolean; + + /** + * Turns automatic skew correction on and off. + * @type {bool} + */ + IfAutomaticDeskew: boolean; + + /** + * Returns or sets whether the Source enables the automatic document scanning process. This is a runtime property. + * @type {bool} + */ + IfAutoScan: boolean; + + /** + * Returns or sets whether close the Data Source User Interface after acquire all images. Default value of this property is FALSE. + * @type {bool} + */ + IfDisableSourceAfterAcquire: boolean; + + /** + * Returns or sets whether the Source supports duplex. If TRUE, the scanner scans both sides of a paper; otherwise, the scanner will scan only one side of the image. This is a runtime property. + * @type {bool} + */ + IfDuplexEnabled: boolean; + + /** + * Returns or sets whether the Automatic Document Feeder (ADF) is enabled. This is a runtime property. + * @type {bool} + */ + IfFeederEnabled: boolean; + + /** + * Returns whether or not there are documents loaded in the Source's feeder when IfFeederEnabled and IfPaperDetectable are TRUE. This is a runtime, read-only property. + * @type {bool} + */ + IfFeederLoaded: boolean; + + /** + * Returns or sets whether to resize the image to fit the size of window when the view mode is set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {bool} + */ + IfFitWindow: boolean; + + /** + * [Deprecated.] Returns or sets whether the UI (User Interface) of Source runs in modal state. Default value of this property is TRUE. + * @type {bool} + */ + IfModalUI: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses Graphics Device Interface (GDI) when decoding images. + * @type {bool} + */ + IfOpenImageWithGDIPlus: boolean; + + /** + * Returns the value whether the Source has a paper sensor that can detect documents on the ADF or Flatbed. This is a runtime, read-only property. + * @type {bool} + */ + IfPaperDetectable: boolean; + + /** + * Returns or sets whether FTP passive mode is enabled. + * @type {bool} + */ + IfPASVMode: boolean; + + /** + * [Deprecated.] Returns or sets whether communicate with device in a separate thread. Default value of this property is FALSE. + * @type {bool} + */ + IfScanInNewThread: boolean; + + /** + * Sets or returns whether to show the cancel dialog when uploading images to server. + * @type {bool} + */ + IfShowCancelDialogWhenImageTransfer: boolean; + + /** + * Returns or sets whether to show the file dialog box when saving scanned images or loading images from local folder. + * @type {bool} + */ + IfShowFileDialog: boolean; + + /** + * Returns or sets whether the Source displays a progress indicator during acquisition and transfer, regardless of whether the Source's user interface is active. This is a runtime property. + * @type {bool} + */ + IfShowIndicator: boolean; + + /** + * [Deprecated.] Returns or sets whether the driver of the printer displays the User Interface. + * @type {bool} + */ + IfShowPrintUI: boolean; + + /** + * Returns or sets whether the progress bar will be displayed during the transaction. This is a runtime property. + * @type {bool} + */ + IfShowProgressBar: boolean; + + /** + * Returns or sets whether the Source displays the User Interface. + * @type {bool} + */ + IfShowUI: boolean; + + /** + * Returns or sets whether SSL is used when uploading or downloading images. + * @type {bool} + */ + IfSSL: boolean; + + /** + * Return or sets whether the Source allows to save many images in one TIFF file. The default value is FALSE. + * @type {bool} + */ + IfTiffMultiPage: boolean; + + /** + * Returns whether the Source supports acquisition with the UI (User Interface) disabled. If FALSE, indicates that this Source can only support acquisition with the UI enabled. This is a runtime, read-only property. + * @type {bool} + */ + IfUIControllable: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses the new TWAIN Data Source Manager (TWAINDSM.dll) when acquiring images from TWAIN devices. + * @type {bool} + */ + IfUseTwainDSM: boolean; + + /** + * Specifies whether or not to automatically scroll to the last image or stay on the current image when loading or acquiring images + * @type {bool} + */ + IfAutoScroll: boolean; + + /** + * [Deprecated.] The number of bits in each image pixel (or bit depth). This is a runtime, read-only property. + * @type {short} + */ + ImageBitsPerPixel: number; + + /** + * Returns or sets whether a TWAIN driver or Native Scan of Mac OS X is used for document scanning. This property works for Mac edition only. + * @type {int} + */ + ImageCaptureDriverType: number; + + /** + * [Deprecated.] Returns or sets whether the image enumerator is enabled in Image Editor. + * @type {bool} + */ + ImageEditorIfEnableEnumerator: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is a modal window. + * @type {bool} + */ + ImageEditorIfModal: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is read-only. + * @type {bool} + */ + ImageEditorIfReadonly: boolean; + + /** + * [Deprecated.] Returns or sets the title of Image Editor window. + * @type {string} + */ + ImageEditorWindowTitle: string; + + /** + * Returns the document number of the current image. This is a runtime, read-only property. + * @type {int} + */ + ImageLayoutDocumentNumber: number; + + /** + * Returns the value of the bottom-most edge of the current image frame (in Unit). This is a read-only runtime property. + * @type {float} + */ + ImageLayoutFrameBottom: number; + + /** + * Returns the value of the left-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameLeft: number; + + /** + * Returns the frame number of the current image. This is a runtime, read-only property. + * @type {int} + */ + ImageLayoutFrameNumber: number; + + /** + * Returns the value of the right-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameRight: number; + + /** + * Returns the value of the top-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameTop: number; + + /** + * Returns the page number of the current image. This is a runtime, read-only property. + * @type {Long} + */ + ImageLayoutPageNumber: number; + + /** + * [Deprecated.] Returns how tall/long, in pixels, the image is. This is a runtime, read-only property. + * @type {int} + */ + ImageLength: number; + + /** + * Returns or sets the margin between images when multiple images are displayed in Dynamic Web TWAIN. + * @type {short} + */ + ImageMargin: number; + + /** + * Returns the pixel type of the current image. This is a runtime, read-only property. Please note the property is only valid in OnPreTransfer and OnPostTransfer event. + * @type {EnumDWT_PixelType} + */ + ImagePixelType: EnumDWT_PixelType; + + /** + * [Deprecated.] Returns how width, in pixels, the image is. This is a runtime, read-only property. + * @type {int} + */ + ImageWidth: number; + + /** + * [Deprecated.] Returns the X resolution of the current image. X resolution is the number of pixels per Unit in the horizontal direction. This is a runtime, read-only property. + * @type {float} + */ + ImageXResolution: number; + + /** + * [Deprecated.] Returns the Y resolution of the current image. Y resolution is the number of pixels per Unit in the vertical direction. This is a runtime, read-only property. + * @type {float} + */ + ImageYResolution: number; + + /** + * Returns or sets the quality of JPEG files and PDF files using JPEG compression. + * @type {short} + */ + JPEGQuality: number; + + /** + * Returns or sets the log level for debugging. + * @type {short} + */ + LogLevel: number; + + /** + * Return the magnetic data if the scanner support magnetic data recognition. + * @type {string} + */ + MagData: string; + + /** + * Return the magnetic type if the scanner support magnetic data recognition. + * @type {short} + */ + MagType: number; + + /** + * Sets or returns the manufacture string for the application identity. + * @type {string} + */ + Manufacturer: string; + + /** + * Returns or sets the maximum number of images can be held in buffer. + * @type {short} + */ + MaxImagesInBuffer: number; + + /** + * [Deprecated.] Returns or sets how many threads can be used when you upload files through POST. + * @type {int} + */ + MaxInternetTransferThreads: number; + + /** + * Sets or returns the maximum allowed size when Dynamic Web TWAIN uploads a document. + * @type {int} + */ + MaxUploadImageSize: number; + + /** + * Returns or sets the shape of the mouse. + * @type {bool} + */ + MouseShape: boolean; + + /** + * Returns the X co-ordinate of the mouse. This is a runtime property. + * @type {int} + */ + MouseX: number; + + /** + * Returns the Y co-ordinate of the mouse. This is a runtime property. + * @type {int} + */ + MouseY: number; + + /** + * Returns or sets the page size(s) the Source can/should use to acquire image data. This is a runtime property. + * @type {short} + */ + PageSize: number; + + /** + * Returns or sets the name of the person who creates the PDF document. + * @type {string} + */ + PDFAuthor: string; + + /** + * Returns or sets the compression type of PDF files. This is a runtime property. + * @type {EnumDWT_PDFCompressionType} + */ + PDFCompressionType: EnumDWT_PDFCompressionType; + + /** + * Returns or sets the date when the PDF document is created. + * @type {string} + */ + PDFCreationDate: string; + + /** + * Returns or sets the name of the application that created the original document, if the PDF document is converted from another form. + * @type {string} + */ + PDFCreator: string; + + /** + * Returns or sets the keywords associated with the PDF document. + * @type {string} + */ + PDFKeywords: string; + + /** + * Returns or sets the date when the PDF document is last modified. + * @type {string} + */ + PDFModifiedDate: string; + + /** + * Returns or sets the name of the application that converted the PDF document from its native. + * @type {string} + */ + PDFProducer: string; + + /** + * Returns or sets the subject of the PDF document. + * @type {string} + */ + PDFSubject: string; + + /** + * Returns or sets the title of the PDF document. + * @type {string} + */ + PDFTitle: string; + + /** + * Returns or sets the value of the PDF version. + * @type {string} + */ + PDFVersion: string; + + /** + * Returns the number of transfers the Source is ready to supply, upon demand. This is a runtime, read-only property. + * @type {short} + */ + PendingXfers: number; + + /** + * Returns or sets the pixel flavor for acquired images. This is a runtime property. + * @type {short} + */ + PixelFlavor: number; + + /** + * Returns or sets the pixel type of current data source. This is a runtime property. Using this property after calling OpenSource() method and before calling AcquireImage(). + * @type {EnumDWT_PixelType} + */ + PixelType: EnumDWT_PixelType; + + /** + * Sets or returns the product family string for the application identity. + * @type {string} + */ + ProductFamily: string; + + /** + * Sets the product key. A product key is generated in Licensing Tool which is intalled with Dynamic Web TWAIN. Each product key corresponds with a license. + * @type {string} + */ + ProductKey: string; + + /** + * [Deprecated.] Returns or sets the name of the proxy server. + * @type {string} + */ + ProxyServer: string; + + /** + * Returns or sets the current resolution for acquired images. This is a runtime property. + * @type {float} + */ + Resolution: number; + + /** + * Returns or sets how many scanned images are selected. + * @type {short} + */ + SelectedImagesCount: number; + + /** + * Returns or sets the border color of the selected image. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + SelectionImageBorderColor: number; + + /** + * Specifies a fixed aspect ratio to be used for selecting an area. + * @type {float} + */ + SelectionRectAspectRatio: number; + + /** + * Returns how many sources are installed in the system. This is a runtime, read-only property. + * @type {int} + */ + SourceCount: number; + + /** + * [Deprecated.] Replaced by GetSourceNameItems method. + * @type {string} + */ + SourceNameItems: string; + + /** + * [Deprecated.] + * @type {string} + */ + GetSourceNames: string; + + /** + * Returns or sets the compression type of TIFF files. This is a runtime property. + * @type {EnumDWT_TIFFCompressionType} + */ + TIFFCompressionType: EnumDWT_TIFFCompressionType; + + /** + * Sets or returns the transfer mode. + * @type {EnumDWT_TransferMode} + */ + TransferMode: EnumDWT_TransferMode; + + /** + * Returns or sets the unit of measure. This is a runtime property. + * @type {short} + */ + Unit: number; + + /** + * Sets or returns the version info string for the application identity. + * @type {string} + */ + VersionInfo: string; + + /** + * Returns and sets the number of images you are willing to transfer per session. This is a runtime property. + * @type {short} + */ + XferCount: number; + + /** + * Returns or sets zoom factor for the image, only valid When the view mode is set to -1 by -1. + * @type {float} + */ + Zoom: number; + + /** + * Binds a specified function to an event, so that the function gets called whenever the event fires. + * @method WebTwain#RegisterEvent + * @param {string} name the name of the event that the function is bound to. + * @param {object} evt specifies the function to call when event fires. + * @return {bool} + */ + RegisterEvent(name: string, evt: object): boolean; + + // --- SCAN start -- + + /** + * Cancels all pending transfers. + * @method WebTwain#CancelAllPendingTransfers + * @return {bool} + */ + CancelAllPendingTransfers(): boolean; + + /** + * Closes Data Source. + * @method WebTwain#CloseSource + * @return {bool} + */ + CloseSource(): boolean; + + /** + * Closes and unloads Data Source Manager. + * @method WebTwain#CloseSourceManager + * @return {bool} + */ + CloseSourceManager(): boolean; + + /** + * Disable the source. If the source's user interface is displayed when the source is enabled, it will be closed. + * @method WebTwain#DisableSource + * @return {bool} + */ + DisableSource(): boolean; + + /** + * Sets the Source to eject the current page and advance the next page in the document feeder into the feeder acquire area when IfFeederEnabled is TRUE. + * @method WebTwain#FeedPage + * @return {bool} + */ + FeedPage(): boolean; + + /** + * Retrieve the device type of the currently selected data source, it might be a scanner, a web camera, etc. + * @method WebTwain#GetDeviceType + * @return {int} + */ + GetDeviceType(): number; + + /** + * Get the source name according to the source index. + * @method WebTwain#GetSourceNameItems + * @param {short} index int index. Index is 0-based and can not be greater than SourceCount property. + * @return {string} + */ + GetSourceNameItems(index: number): string; + + /** + * Loads the specified Source into main memory and causes its initialization, + * placing Dynamic Web TWAIN into Capability Negotiation state. If no source is + * specified (no SelectSource() or SelectSourceByIndex() is called), opens the default source. + * @method WebTwain#OpenSource + * @return {bool} + */ + OpenSource(): boolean; + + /** + * Loads and opens Data Source Manager. + * @method WebTwain#OpenSourceManager + * @return {bool} + */ + OpenSourceManager(): boolean; + + /** + * Reverts the current image layout to the Data Source's default. + * @method WebTwain#ResetImageLayout + * @return {bool} + */ + ResetImageLayout(): boolean; + + /** + * Sets the Source to return the current page to the input side of the document feeder and + * feed the last page from the outside of the feeder back into the acquisition area if IfFeederEnabled is TRUE. + * @method WebTwain#RewindPage + * @return {bool} + */ + RewindPage(): boolean; + + /** + * Brings up the TWAIN Data Source Manager's Source Selection User Interface (UI) + * so that user can choose which Data Source to be the current Source. + * @method WebTwain#SelectSource + * @return {bool} + */ + SelectSource(): boolean; + + /** + * Selects the index-the source in SourceNameItems property as the current source. + * @method WebTwain#SelectSourceByIndex + * @param {short} index It is the index of SourceNameItems property. + * @return {bool} + */ + SelectSourceByIndex(index: number): boolean; + + /** + * Sets file name and file format information used in File Transfer Mode. + * @method WebTwain#SetFileXferInfo + * @param {string} fileName the name of the file to be used in transfer. + * @param {EnumDWT_FileFormat} fileFormat an enumerated value indicates the format of the image. + * @return {bool} + */ + SetFileXferInfo(fileName: string, fileFormat: EnumDWT_FileFormat): boolean; + + /** + * Sets the left, top, right, and bottom sides of the image layout rectangle for the current Data Source. + * @method WebTwain#SetImageLayout + * @param {float} left specifies the floating point number for the left side of the image layout rectangle. + * @param {float} top specifies the floating point number for the top side of the image layout rectangle. + * @param {float} right specifies the floating point number for the right side of the image layout rectangle. + * @param {float} bottom specifies the floating point number for the bottom side of the image layout rectangle. + * @return {bool} + */ + SetImageLayout(left: number, top: number, right: number, bottom: number): boolean; + + /** + * Clears all the web forms which are used for image uploading. + * @method WebTwain#ClearAllHTTPFormField + * @return {bool} + */ + ClearAllHTTPFormField(): boolean; + + /** + * Clears the content of all custom tiff tags. + * @method WebTwain#ClearTiffCustomTag + * @return {void} + */ + ClearTiffCustomTag(): void; + + /** + * Check whether a certain file exists on the local disk. + * @method WebTwain#FileExists + * @param {string} localFile specifies the absolute path of the local file. + * @return {bool} + */ + FileExists(localFile: string): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownload + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownload(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly download a file from the FTP server to local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPDownloadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {string} localFile specify a full path to store the file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownloadDirectly(FTPServer: string, FTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownloadEx + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {EnumDWT_ImageType} lImageType simage format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownloadEx(FTPServer: string, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server. + * @method WebTwain#FTPUpload + * @param {string} FTPServer the name of the FTP server. + * @param {short} sImageIndex specifies the index of the image in the buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUpload(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly upload a specific file to the FTP server without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPUploadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} localFile specify the the full path of a local file. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadDirectly(FTPServer: string, localFile: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server as a specified image format. + * @method WebTwain#FTPUploadEx + * @param {string} FTPServer the name of the FTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadEx(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAllAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAllAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAllAsPDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAllAsPDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAsMultiPagePDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAsMultiPagePDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownload + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the name of the image to be downloaded. It should be the relative path of the file on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownload(HTTPServer: string, HTTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly downloads a file from the HTTP server to a local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPDownloadDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile The relative path of the file on the HTTP server. + * @param {string} localFile specify the location to store the downloaded file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadDirectly(HTTPServer: string, HTTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownloadEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadEx(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Download an image from the server using a HTTP Post call. + * @method WebTwain#HTTPDownloadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadThroughPost(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the HTTP server through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPost(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly upload a specific local file to the HTTP server through the HTTP POST method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPostDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file . + * @param {string} ActionPage the specified page for posting files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the file to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostDirectly(HTTPServer: string, localFile: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPostEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server.s + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostEx(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadAllThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPostAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadAllThroughPostAsPDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostAsMultiPagePDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Directly uploads a specific local file to the HTTP server through the HTTP PUT method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPutDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutDirectly(HTTPServer: string, localFile: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPut + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the image to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPut(HTTPServer: string, sImageIndex: number, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPutEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutEx(HTTPServer: string, sImageIndex: number, RemoteFileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadAllThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPutAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadAllThroughPutAsPDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutAsMultiPagePDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Configures how segmented upload is done. + * @method WebTwain#SetUploadSegment + * @param {int} segmentUploadThreshold specifies the threshold (in MB) over which segmented upload will be invoked. + * @param {int} moduleSize specifies the size of each segment (in KB). + * @return {bool} + */ + SetUploadSegment (segmentUploadThreshold: number, moduleSize: number): boolean; + + /** + * Uploads the images specified by the indices to the HTTP server. + * @method WebTwain#HTTPUpload + * @param {string} url the url where the images are sent in a POST request. + * @param {Array} indices indices specifies which images are to be uploaded. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. + * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUpload (url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads a DIB format image from Clipboard into the Dynamic Web TWAIN. + * @method WebTwain#LoadDibFromClipboard + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadDibFromClipboard(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImage + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadImage(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImageEx + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be loaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadImageEx(localFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads image from a base64 byte array with the specified file format. + * @method WebTwain#LoadImageFromBase64Binary + * @param {string} bry specifies the base64 string data. + * @param {EnumDWT_ImageType} lImageType specifies the file format. + * @return {bool} + */ + LoadImageFromBase64Binary(bry: string, lImageType: EnumDWT_ImageType): boolean; + + /** + * [Deprecated.] Loads image from a byte array with the specified file format. + * @method WebTwain#LoadImageFromBytes + * @param {int} lBufferSize Specifies the buffer size. + * @param {Array} buffer A byte array of the image data. + * @param {EnumDWT_ImageType} lImageType Specifies the file format. + * @return {bool} + */ + LoadImageFromBytes(lBufferSize: number, buffer: number[], lImageType: EnumDWT_ImageType): boolean; + + /** + * Saves all images in buffer as a MultiPage TIFF file. + * @method WebTwain#SaveAllAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveAllAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves all images in buffer as a Multi-Page PDF file. + * @method WebTwain#SaveAllAsPDF + * @param {string} localFile the name of the Multi-Page PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveAllAsPDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a BMP file. + * @method WebTwain#SaveAsBMP + * @param {string} localFile the name of the BMP file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsBMP(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a JPEG file. + * @method WebTwain#SaveAsJPEG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsJPEG(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a PDF file. + * @method WebTwain#SaveAsPDF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsPDF(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a PNG file. + * @method WebTwain#SaveAsPNG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsPNG(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a TIFF file. + * @method WebTwain#SaveAsTIFF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsTIFF(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the selected images in buffer as a Multipage PDF file. + * @method WebTwain#SaveSelectedImagesAsMultiPagePDF + * @param {string} localFile the name of the MultiPage PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveSelectedImagesAsMultiPagePDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer as a Multipage TIFF file. + * @method WebTwain#SaveSelectedImagesAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveSelectedImagesAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer to base64 string. + * @method WebTwain#SaveSelectedImagesToBase64Binary + * @return {string} + */ + SaveSelectedImagesToBase64Binary(): string; + + /** + * [Deprecated.] Saves the selected images in buffer to a byte array in the specified file format. + * @method WebTwain#SaveSelectedImagesToBytes + * @param {int} bufferSize specified the buffer size. + * @param {Array} buffer A byte array of the image data. + * @return {int} + */ + SaveSelectedImagesToBytes(bufferSize: number, buffer: number[]): number; + + /** + * [Deprecated.] Sets current cookie into the Http Header to be used when uploading scanned images through POST. + * @method WebTwain#SetCookie + * @param {string} cookie the cookie on current page. + * @return {void} + */ + SetCookie(cookie: string): void; + + /** + * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. + * @method WebTwain#SetHTTPFormField + * @param {string} FieldName specifies the name of a text field in web form. + * @param {string} FieldValue specifies the value of a text field in web form. + * @return {bool} + */ + SetHTTPFormField(FieldName: string, FieldValue: string): boolean; + + /** + * Sets a custom tiff tag. Currently you can set up to 32 tags. The string to be set in a tag can be encoded with base64. + * @method WebTwain#SetTiffCustomTag + * @param {int} tag specifies the tag identifier. The value should be between 600 and 700. + * @param {string} content the string to be set for this tag. The string will be written to the .tiff file when you save/upload it. If the string is base64 encoded, we'll decode it before writing it. + * @param {bool} base64Str if you'd like to encode the string with base64, set this to true. Otherwise, the string will be plin text. + * @return {bool} + */ + SetTiffCustomTag(tag: number, content: string, base64Str: boolean): boolean; + + /** + * Show save file dialog or show open file dialog. + * @method WebTwain#ShowFileDialog + * @param {bool} SaveDialog True -- show save file dialog, False -- show open file dialog. + * @param {string} Filter The filter name specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid file name characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. To retrieve a shortcut's target without filtering, use the string "All Files\0*.*\0\0", but the program will replace "\0" with "|" automatically. + * @param {int} FilterIndex The index of the currently selected filter in the File Types control. The buffer pointed to by Filter contains pairs of strings that define the filters. The index is 0-based. + * @param {string} DefExtension Define the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name only if the user fails to type an extension. If this member is NULL and the user fails to type an extension, no extension is appended. + * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. + * @param {bool} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. + * @param {bool} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. + * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @return {bool} + */ + ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; + + /** + * Gets information of the capability specified by the Capability property. + * @method WebTwain#CapGet + * @return {bool} + */ + CapGet(): boolean; + + /** + * Returns the Source's current Value for the specified capability. + * @method WebTwain#CapGetCurrent + * @return {bool} + */ + CapGetCurrent(): boolean; + + /** + * Returns the Source's Default Value for the specified capability. This is the Source's preferred default value. + * @method WebTwain#CapGetDefault + * @return {bool} + */ + CapGetDefault(): boolean; + + /** + * Returns the value of the bottom-most edge of the specified frame. + * @method WebTwain#CapGetFrameBottom + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameBottom(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameLeft + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameLeft(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameRight + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameRight(index: number): number; + + /** + * Returns the value (in Unit) of the top-most edge of the specified frame. + * @method WebTwain#CapGetFrameTop + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameTop(index: number): number; + + /** + * Queries whether the Source supports a particular operation on the capability. + * @method WebTwain#CapIfSupported + * @param {EnumDWT_MessageType} messageType specifies the type of capability operation. + * @return {bool} + */ + CapIfSupported(messageType: EnumDWT_MessageType): boolean; + + /** + * Changes the Current Value of the capability specified by Capability property back to its power-on value. + * @method WebTwain#CapReset + * @return {bool} + */ + CapReset(): boolean; + + /** + * Sets the current capability using the container type specified by CapType property. The current capability is specified by Capability property. + * @method WebTwain#CapSet + * @return {bool} + */ + CapSet(): boolean; + + /** + * Sets the values of the specified frame. + * @method WebTwain#CapSetFrame + * @param {short} index specifies the values of which frame to set. The index is 0-based. + * @param {float} left the value (in Unit) of the left-most edge of the specified frame. + * @param {float} top the value (in Unit) of the top-most edge of the specified frame. + * @param {float} right the value (in Unit) of the right-most edge of the specified frame. + * @param {float} bottom the value (in Unit) of the bottom-most edge of the specified frame. + * @return {bool} + */ + CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Get the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItems + * @param {int} index Index is 0-based. It is the index of the cap item. + * @return {double} + */ + GetCapItems(index: number): number; + + /** + * Returns the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItemsString + * @param {int} index Index is 0-based. It is the index of the cap item. + * @return {string} + */ + GetCapItemsString(index: number): string; + + /** + * Set the value of the specified cap item. + * @method WebTwain#SetCapItems + * @param {int} index Index is 0-based. It is the index of the cap item. + * @param {double} newVal The Double type of CapItems property is used to present Double, Single(float), Long, int and even boolean types. For string type, please use CapItemsstring property. + * @return {void} + */ + SetCapItems(index: number, newVal: number): void; + + /** + * Set the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#SetCapItemsString + * @param {int} index Index is 0-based. It is the index of the cap item. + * @param {string} newVal The new value to be set. + * @return {void} + */ + SetCapItemsString(index: number, newVal: string): void; + // --- SCAN end -- + + // --- View & Edit start -- + + /** + * Add text on an image. + * @method WebTwain#AddText + * @param {short} sImageIndex the index of the image that you want to add text to. + * @param {int} x the x coordinate for the text. + * @param {int} y the y coordinate for the text. + * @param {string} text the content of the text that you want to add. + * @param {int} txtColor the color for the text. + * @param {int} backgroundColor the background color. + * @param {float} backgroundRoundRadius ranging from 0 to 0.5. Please NOTE that MAC version does not support this parameter. + * @param {float} backgroundOpacity specifies the opacity of the background of the added text, it ranges from 0 to 1.0. Please NOTE that Mac version only supports value 0 and 1 + * @return {bool} + */ + AddText(sImageIndex: number, x: number, y: number, text: string, txtColor: number, backgroundColor: number, backgroundRoundRadius: number, backgroundOpacity: number): boolean; + + /** + * Create the font for adding text using the method AddText. + * @method WebTwain#CreateTextFont + * @param {int} height Specifies the desired height (in logical units) of the font.The absolute value of nHeight must not exceed 16,384 device units after it is converted.For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size. + * @param {int} width Specifies the average width (in logical units) of characters in the font. If Width is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference. + * @param {int} escapement Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis. + * @param {int} orientation Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis.The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up. + * @param {int} weight Specifies the font weight (in inked pixels per 1000). The described valuesare approximate; the actual appearance depends on the typeface. Some fonts haveonly FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used. + * @param {short} italic Specifies an italic font if set to TRUE. + * @param {short} underline Specifies an underlined font if set to TRUE. + * @param {short} strikeOut A strikeout font if set to TRUE. + * @param {short} charSet Specifies the font's character set. The OEM character set is system-dependent. Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. + * @param {short} outputPrecision Specifies the desired output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, and pitch. + * @param {short} clipPrecision Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. + * @param {short} quality Specifies the font's output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. + * @param {short} pitchAndFamily The pitch and family of the font. + * @param {string} faceName the typeface name, the length of this string must not exceed 32 characters, including the terminating null character. + * @return {bool} + */ + CreateTextFont(height: number, width: number, escapement: number, orientation: number, weight: number, italic: number, underline: number, strikeOut: number, charSet: number, outputPrecision: number, clipPrecision: number, quality: number, pitchAndFamily: number, faceName: string): boolean; + + /** + * Copies the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CopyToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + CopyToClipboard(sImageIndex: number): boolean; + + /** + * Clears the specified area of a specified image, and fill the area with the fill color. + * @method WebTwain#Erase + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + Erase(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Returns the pixel bit depth of the selected image. + * @method WebTwain#GetImageBitDepth + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {short} + */ + GetImageBitDepth(sImageIndex: number): number; + + /** + * Returns the width (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageWidth + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {int} + */ + GetImageWidth(sImageIndex: number): number; + + /** + * Returns the height (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageHeight + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {int} + */ + GetImageHeight(sImageIndex: number): number; + + /** + * Returns the file size of the new image resized from the image of a specified index in buffer. + * @method WebTwain#GetImageSize + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} iWidth specifies the pixel width of the new image. + * @param {int} iHeight specifies the pixel height of the new image. + * @return {double} + */ + GetImageSize(sImageIndex: number, iWidth: number, iHeight: number): number; + + /** + * Pre-calculate the file size of the local image file that is saved from an image of a specified index in buffer. + * @method WebTwain#GetImageSizeWithSpecifiedType + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {short} sImageType specifies the type of an image file.. + * @return {int} + */ + GetImageSizeWithSpecifiedType(sImageIndex: number, sImageType: number): number; + + /** + * Return the horizontal resolution of the specified image. + * @method WebTwain#GetImageXResolution + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {int} + */ + GetImageXResolution(sImageIndex: number): number; + + /** + * Return the vertical resolution of the specified image. + * @method WebTwain#GetImageYResolution + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {int} + */ + GetImageYResolution(sImageIndex: number): number; + + /** + * Returns the index of the selected image. + * @method WebTwain#GetSelectedImageIndex + * @param {short} sSelectedIndex specifies the index of the selected image. + * @return {short} + */ + GetSelectedImageIndex(sSelectedIndex: number): number; + + /** + * You can use the method to select images programatically which is ususally done by mouse clicking. + * @method WebTwain#SetSelectedImageIndex + * @param {short} sSelectedIndex this is the index of an array that holds the indices of selected images. + * @param {short} newVal specifies the index of an image that you want to select. + * @return {void} + */ + SetSelectedImageIndex(selectedIndex: number, newVal: number): void; + + /** + * Pre-calculate the file size of the local image file that is saved from the selected images in buffer. + * @method WebTwain#GetSelectedImagesSize + * @param {int} iImageType specifies the type of an image file. + * @return {int} + */ + GetSelectedImagesSize(iImageType: number): number; + + /** + * Check the skew angle of an image by its index in buffer. + * @method WebTwain#GetSkewAngle + * @param {short} sImageIndex the index of the image in the buffer. + * @return {double} + */ + GetSkewAngle(sImageIndex: number): number; + + /** + * Check the skew angle of a rectangular part of an image by its index in buffer. + * @method WebTwain#GetSkewAngleEx + * @param {short} sImageIndex the index of the image in the buffer. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {double} + */ + GetSkewAngleEx(sImageIndex: number, left: number, top: number, right: number, bottom: number): number; + + /** + * [Deprecated.] Detects whether a certain area on an image is blank. + * @method WebTwain#IsBlankImageEx + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {bool} bFuzzyMatch specifies whether use fuzzy matching when detecting. + * @return {bool} + */ + IsBlankImageEx(sImageIndex: number, left: number, top: number, right: number, bottom: number, bFuzzyMatch: boolean): boolean; + + /** + * Mirrors the image of a specified index in buffer. + * @method WebTwain#Mirror + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + Mirror(sImageIndex: number): boolean; + + /** + * Decorates image of a specified index in buffer with rectangles of transparent color. + * @method WebTwain#OverlayRectangle + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {int} color Specifies the fill color of the rectangle. The byte-ordering of the RGB value is 0xBBGGRR. BB represents blue, GG represents green, RR represents red. + * @param {float} fOpacity Specifies the opacity of the rectangle. The value represents opacity. 1.0 is 100% opaque and 0.0 is totally transparent. + * @return {bool} + */ + OverlayRectangle(sImageIndex: number, left: number, top: number, right: number, bottom: number, color: number, fOpacity: number): boolean; + + /** + * Removes all images in buffer. + * @method WebTwain#RemoveAllImages + * @return {void} + */ + RemoveAllImages(): void; + + /** + * Removes selected images in buffer. + * @method WebTwain#RemoveAllSelectedImages + * @return {bool} + */ + RemoveAllSelectedImages(): boolean; + + /** + * Removes the image of a specified index in buffer. + * @method WebTwain#RemoveImage + * @param {short} sImageIndexToBeDeleted specifies the index of the image to be deleted in buffer. The index is 0-based. + * @return {bool} + */ + RemoveImage(sImageIndexToBeDeleted: number): boolean; + + // Image Operate + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#Rotate + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {float} fAngle Specifies the rotation angle. + * @param {bool} bKeepSize Keep size or not. + * @return {bool} + */ + Rotate(sImageIndex: number, fAngle: number, bKeepSize: boolean): boolean; + + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#RotateEx + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {float} fAngle Specifies the rotation angle. + * @param {bool} bKeepSize Keep size or not. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + RotateEx(sImageIndex: number, fAngle: number, bKeepSize: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees counter-clockwise. + * @method WebTwain#RotateLeft + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + RotateLeft(sImageIndex: number): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees clockwise. + * @method WebTwain#RotateRight + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + RotateRight(sImageIndex: number): boolean; + + /** + * Changes width and height of the image of a specified index in the buffer. Please note the file size of the image will be changed proportionately. + * @method WebTwain#ChangeImageSize + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} iNewWidth specifies the pixel width of the new image. + * @param {int} iNewHeight specifies the pixel height of the new image. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + ChangeImageSize(sImageIndex: number, iNewWidth: number, iNewHeight: number, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Flips the image of a specified index in buffer. + * @method WebTwain#Flip + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + Flip(sImageIndex: number): boolean; + + /** + * Crops the image of a specified index in buffer. + * @method WebTwain#Crop + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + Crop(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Crops the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CropToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + CropToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image data in the specified area to the system clipboard in DIB format. + * @method WebTwain#CutFrameToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + CutFrameToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CutToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + CutToClipboard(sImageIndex: number): boolean; + + /** + * Change the DPI (dots per inch) for the specified image. + * @method WebTwain#SetDPI + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} xResolution The horizontal resolution. + * @param {int} yResolution The vertical resolution. + * @param {bool} bResampleImage Whether to resample the image. (The image size will be changed if this is set to true). + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + SetDPI(sImageIndex: number, xResolution: number, yResolution: number, bResampleImage: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Sets the view mode that images are displayed in Dynamic Web TWAIN. You can use this method to display multiple images in Dynamic Web TWAIN. + * @method WebTwain#SetViewMode + * @param {short} sHorizontalImageCount specifies how many columns can be displayed in Dynamic Web TWAIN. + * @param {short} sVerticalImageCount specifies how many rows can be displayed in Dynamic Web TWAIN.. + * @return {void} + */ + SetViewMode(sHorizontalImageCount: number, sVerticalImageCount: number): void; + + /** + * Moves a specified image. + * @method WebTwain#MoveImage + * @param {short} sSourceImageIndex Specifies the source index of image in buffer. The index is 0-based. + * @param {short} sTargetImageIndex Specifies the target index of image in buffer. The index is 0-based. + * @return {bool} + */ + MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; + + /** + * Switchs two images of specified indices in buffer. + * @method WebTwain#SwitchImage + * @param {short} sImageIndex1 specifies the index of image in buffer. The index is 0-based. + * @param {short} sImageIndex2 specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SwitchImage(sImageIndex1: number, sImageIndex2: number): boolean; + + /** + * Shows the GUI of Image Printer. + * @method WebTwain#Print + * @return {bool} + */ + Print(): boolean; + // --- View & Edit end -- + + // --- Upload & Save end -- + + // --- Others --- + /** + * Shows the GUI of Image Editor. + * @method WebTwain#ShowImageEditor + * @return {bool} + */ + ShowImageEditor(): boolean; + + /** + * Unbinds an event from the specified function, so that the function stops receiving notifications when the event fires. + * @method WebTwain#UnregisterEvent + * @param {string} name the name of the event. + * @param {object} evt specified the function to be unbound. + * @return {bool} + */ + UnregisterEvent(name: string, evt: object): boolean; + // --- Others end --- + + /** + * Enables the source to accept image. + * @method WebTwain#EnableSource + * @return {bool} + */ + EnableSource(): boolean; + + /** + * Displays the source's built-in interface to acquire image. + * @method WebTwain#AcquireImage + * @param {object} optionalDeviceConfig a JS object used to set up the device for image acquisition. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + AcquireImage(optionalDeviceConfig?: object, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + // start from 10.0 + /** + * Change the width of an image in buffer. + * @method WebTwain#SetImageWidth + * @param {short} sImageIndex specifies which image you'd like to change. + * @param {int} iNewWidth specifies how wide you'd like to change the image. + * @return {bool} + */ + SetImageWidth(sImageIndex: number, iNewWidth: number): boolean; + + // Set custom DS data (DAT_CUSTOMDSDATA), the input string is encoded with base64 + /** + * Sets custom DS data to be used for scanning, the input string is encoded with base64. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSDataEx + * @param {string} value the input string which is encoded with base64. + * @return {bool} + */ + SetCustomDSDataEx(value: string): boolean; + + // Set custom DS data, load data from the specified file + /** + * Sets custom DS data to be used for scanning, the data is stored in a file. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSData + * @param {string} fileName the absolute path of the file where the custom data source data is stored. + * @return {bool} + */ + SetCustomDSData(fileName: string): boolean; + + // Get custom DS data, and returned string is encoded with base64 + /** + * Gets custom DS data, the returned string is base64 encoded. + * @method WebTwain#GetCustomDSDataEx + * @return {string} + */ + GetCustomDSDataEx(): string; + + // Get custom DS data, and save the data to the specified file + /** + * Gets custom DS data and save the data in a specified file. + * @method WebTwain#GetCustomDSData + * @param {string} fileName the path of the file used for storing custom DS data. + * @return {bool} + */ + GetCustomDSData(fileName: string): boolean; + + /** + * Changes the bitdepth of a specified image. + * @method WebTwain#ChangeBitDepth + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {short} sBitDepth specifies the target bit depth. + * @param {bool} bHighQuality specifies whether or not to keep high quality while changing the bit depth. When it's true, it takes more time. + * @return {bool} + */ + ChangeBitDepth(sImageIndex: number, sBitDepth: number, bHighQuality: boolean): boolean; + + /** + * Changes a specified image to gray scale. + * @method WebTwain#ConvertToGrayScale + * @param {short} sIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + ConvertToGrayScale(sIndex: number): boolean; + + /** + * [Deprecated.] Shows the GUI of Image Editor with custom settings. + * @method WebTwain#ShowImageEditorEx + * @param {int} x specifies the new position of the left top corner of the window. + * @param {int} y specifies the new position of the left top corner of the window. + * @param {int} cx specifies the width of the window. + * @param {int} cy specifies the height of the window. + * @param {int} nCmdShow specifices how the window should be shown. + * @return {bool} + */ + ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; + + /** + * [Deprecated.] Detects whether an image is blank. + * @method WebTwain#IsBlankImage + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + IsBlankImage(sImageIndex: number): boolean; + + /** + * Detects whether a specific image is blank. + * @method WebTwain#IsBlankImageExpress + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + IsBlankImageExpress(sImageIndex: number): boolean; + + /** + * [Deprecated.] Detects whether a specific image is blank. + * @method WebTwain#GetBarcodeInfo + * @param {int} barcodeInfoType Defined in TWAIN Specification. + * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. + * @return {object} + */ + GetBarcodeInfo(barcodeInfoType: number, barcodeIndex: number): object; + + /** + * [Deprecated.] Gets the content from a specified barcode. + * @method WebTwain#GetBarcodeText + * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. + * @return {bool} + */ + GetBarcodeText(barcodeIndex: number): boolean; + + /** + * Sets the default source to use. It's only valid when IfUseTWAINDSM is set to true. + * @method WebTwain#SetDefaultSource + * @param {short} sImageIndex specifies the index of the default source. The index is 0-based. + * @return {bool} + */ + SetDefaultSource(sImageIndex: number): boolean; + + /** + * Draws a rectangle on the viewer which represents the selected area. + * @method WebTwain#SetSelectedImageArea + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left The X axis of the left border. + * @param {int} top The Y axis of the top border. + * @param {int} right The X axis of the right border. + * @param {int} bottom The Y axis of the bottom border. + * @return {bool} + */ + SetSelectedImageArea(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Converts the images specified by the indices to base64. + * @method WebTwain#ConvertToBase64 + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Returns the direct URL of an image specified by index, if iWidth or iHeight is set to -1, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. + * @method WebTwain#GetImageURL + * @param {short} index the index of the image. + * @param {int} iWidth the width of the image. + * @param {int} iHeight the height of the image. + * @return {string} + */ + GetImageURL(index: number, iWidth: number, iHeight: number): string; + + /** + * Sets a header for the current HTTP Post request. + * @method WebTwain#SetHTTPHeader + * @param {string} key the key of the header. + * @param {string} value the value of the header. + * @return {bool} + */ + SetHTTPHeader(key: string, value: string): boolean; +} diff --git a/types/path-to-regexp/tsconfig.json b/types/dwt/tsconfig.json similarity index 92% rename from types/path-to-regexp/tsconfig.json rename to types/dwt/tsconfig.json index bee259111e..5ff27b3787 100644 --- a/types/path-to-regexp/tsconfig.json +++ b/types/dwt/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "path-to-regexp-tests.ts" + "dwt-tests.ts" ] } \ No newline at end of file diff --git a/types/dwt/tslint.json b/types/dwt/tslint.json new file mode 100644 index 0000000000..acce7c8a0b --- /dev/null +++ b/types/dwt/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": [false], + "no-trailing-whitespace": false, + "space-before-function-paren": false, + "only-arrow-functions": [false] + } +} diff --git a/types/egg/egg-tests.ts b/types/egg/egg-tests.ts index 921ad35dd7..8caf5f0ac5 100644 --- a/types/egg/egg-tests.ts +++ b/types/egg/egg-tests.ts @@ -9,10 +9,10 @@ class FooController extends Controller { // add user controller and service declare module 'egg' { - interface Controllers { + interface IController { // tslint:disable-line foo: FooController; } - interface Services { + interface IService { // tslint:disable-line foo: FooService; } } diff --git a/types/egg/index.d.ts b/types/egg/index.d.ts index 065c4ee92f..b7746bca0b 100644 --- a/types/egg/index.d.ts +++ b/types/egg/index.d.ts @@ -32,7 +32,7 @@ declare class BaseContextClass { // tslint:disable-line /** * service */ - service: Services; + service: IService; constructor(ctx: Context); } @@ -528,7 +528,7 @@ export interface Application extends EggApplication { redirect(path: string, redirectPath: string): void; - controller: Controllers; + controller: IController; Controller: Controller; } @@ -540,7 +540,7 @@ interface FileStream extends Readable { // tslint:disable-line export interface Context extends KoaApplication.Context { app: Application; - service: Services; + service: IService; request: Request; @@ -762,7 +762,7 @@ export class Controller extends BaseContextClass { } export class Service extends BaseContextClass { } /** - * The empty interface `Services` is an placehoder, for egg + * The empty interface `IService` is an placehoder, for egg * to auto injection service to ctx.service * * @example @@ -773,13 +773,13 @@ export class Service extends BaseContextClass { } * } * * declare module 'egg' { - * export interface service { + * export interface IService { * foo: FooService; * } * } * * Now I can get ctx.service.foo at controller and other service file. */ -export interface Services { }// tslint:disable-line +export interface IService { }// tslint:disable-line -export interface Controllers { } // tslint:disable-line +export interface IController { } // tslint:disable-line diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index 0a715f52bf..e304a73863 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 15.1 +// Type definitions for ej.web.all 15.2 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,7 @@ /*! * filename: ej.web.all.d.ts -* version : 15.1.0.41 +* version : 15.2.0.40 * Copyright Syncfusion Inc. 2001 - 2017. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -247,6 +247,26 @@ declare namespace ej { getFiltersFrom(data: any, query: ej.Query): ej.Predicate; } + class WebMethodAdaptor extends ej.UrlAdaptor { + constructor(); + processQuery(dm: ej.DataManager, query: ej.Query, hierarchyFilters?: any): { + type: string; url: string; ejPvtData: any; contentType?: string; data?: any; + }; + } + + class CacheAdaptor extends ej.UrlAdaptor { + constructor(); + init(adaptor: any, timeStamp: number, pageSize: number): void; + generateKey(url: string, query: ej.Query): string; + processQuery(dm: ej.DataManager, query: ej.Query, hierarchyFilters?: any): any; + processResponse(data: any, ds: any, query: ej.Query, xhr: JQueryXHR, request?: any, changes?: Changes): any; + insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any }; + remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data?: any }; + update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data: any }; + batchRequest(dm: ej.DataManager, changes: Changes, e: any): { url: string; type: string; data: any; contentType: string }; + + } + class ODataAdaptor extends ej.UrlAdaptor { constructor(); options: UrlAdaptorOptions; @@ -9238,6 +9258,44 @@ declare namespace ej { stem?: PositionStem; } + export interface TipSize { + + /** Sets the Tooltip width. + * @Default {20} + */ + width?: number; + + /** Sets the Tooltip height. + * @Default {10} + */ + height?: number; + } + + export interface TipAdjust { + + /** Sets horizontal gap between Tooltip and target element. + * @Default {0} + */ + xValue?: number; + + /** Sets vertical gap between Tooltip and target element. + * @Default {0} + */ + yValue?: number; + } + + export interface Tip { + + /** Sets the Tooltip size. + */ + size?: TipSize; + + /** Sets gap between tooltip against the target element. + */ + adjust?: TipAdjust; + } + + enum effect { ///No animation takes place when showing/hiding the Tooltip @@ -11182,6 +11240,102 @@ declare namespace ej { } } + class Print extends ej.Widget { + static fn: Print; + constructor(element: JQuery | Element, options?: Print.Model); + static Locale: any; + model: Print.Model; + defaults: Print.Model; + + /** Print the specific page or an element. + * @returns {void} + */ + print(): void; + } + + export namespace Print { + + export interface Model { + + /** Append the custom HTML after the selected content. + * @Default {null} + */ + append?: string; + + /** A selector that specifies a particular element to be excluded from printing. + * @Default {null} + */ + excludeSelector?: string; + + /** Specifies whether the URL of an external stylesheet can be included to customize and print that page. + * @Default {null} + */ + externalStyles?: string; + + /** Prepend a doctype to the document frame. + * @Default {<!doctype html>} + */ + docType?: string; + + /** Specifies whether the global styles can be applied to the element to be printed. + * @Default {true} + */ + globalStyles?: boolean; + + /** Sets the height of the print window. + * @Default {454} + */ + height?: number; + + /** Prepends the custom HTML before the selected content. + * @Default {null} + */ + prepend?: string; + + /** Allows printing the content in a new window. + * @Default {false} + */ + printInNewWindow?: boolean; + + /** Sets the period of time to wait before printing the content. + * @Default {1000} + */ + timeOutPeriod?: number; + + /** Sets the title of the print document. + * @Default {null} + */ + title?: string; + + /** Defines the width of the print window. + * @Default {1024} + */ + width?: number; + + /** Event triggers before the document page or an element in it gets printed. */ + beforeStart?(e: BeforeStartEventArgs): void; + } + + export interface BeforeStartEventArgs { + + /** Set this option as true to cancel the event. + */ + cancel?: boolean; + + /** Returns the Print model + */ + model?: ej.Print.Model; + + /** Returns the name of an event + */ + type?: string; + + /** Returns the printed element + */ + content?: any; + } + } + class ProgressBar extends ej.Widget { static fn: ProgressBar; constructor(element: JQuery | Element, options?: ProgressBar.Model); diff --git a/types/element-resize-event/element-resize-event-tests.ts b/types/element-resize-event/element-resize-event-tests.ts index 96c859cdae..5ebf93dcab 100644 --- a/types/element-resize-event/element-resize-event-tests.ts +++ b/types/element-resize-event/element-resize-event-tests.ts @@ -2,6 +2,6 @@ import ere = require("element-resize-event"); var domNode: Element = null; -ere(domNode, (): void => { -}); +ere(domNode, (): void => {}); +ere.unbind(domNode, (): void => {}); diff --git a/types/element-resize-event/index.d.ts b/types/element-resize-event/index.d.ts index e500d2e7f9..4745bc3a11 100644 --- a/types/element-resize-event/index.d.ts +++ b/types/element-resize-event/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for element-resize-event 1.0.1 +// Type definitions for element-resize-event 2.0.9 // Project: https://github.com/KyleAMathews/element-resize-event -// Definitions by: Rogier Schouten +// Definitions by: Rogier Schouten , Pierre-Luc Gregoire // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function elementResizeEvent(domNode: Element, callback: () => void): void; -export = elementResizeEvent; +export = element_resize_event; +declare function element_resize_event(omNode: Element, callback: () => void): void; +declare namespace element_resize_event { + function unbind(omNode: Element, callback: () => void): void; +} diff --git a/types/ember/ember-tests.ts b/types/ember/ember-tests.ts index 99f00aae6f..4119e1d7ec 100644 --- a/types/ember/ember-tests.ts +++ b/types/ember/ember-tests.ts @@ -105,6 +105,17 @@ App.userController = Em.Object.create({ }) }); +Ember.Helper.helper((params) => { + let cents = params[0]; + return `${cents * 0.01}`; +}); + +Ember.Helper.helper((params, hash) => { + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; +}); + Handlebars.registerHelper('highlight', (property: string, options: any) => new Handlebars.SafeString('' + "some value" + '')); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index f7aedcb7c1..201f14f156 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Ember.js 2.7 // Project: http://emberjs.com/ // Definitions by: Jed Mao +// bttf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -548,9 +549,9 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '@each': EachProxy; + '@each': EachProxy; Boolean: boolean; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; @@ -630,8 +631,8 @@ declare namespace Ember { unshiftObject(object: any): any; unshiftObjects(objects: any[]): any[]; without(value: any): Enumerable; - '[]': any[]; - '@each': EachProxy; + '[]': any[]; + '@each': EachProxy; Boolean: boolean; firstObject: any; hasEnumerableObservers: boolean; @@ -1030,7 +1031,7 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; @@ -1137,7 +1138,7 @@ declare namespace Ember { service(name?: string): Service; }; class Helper extends Object { - static helper( h: (a: any) => any): Helper; + static helper( h: (params: any, hash?: any) => any): Helper; compute(params: any[], hash: any): any; recompute(params: any[], hash: any): any; } @@ -1291,7 +1292,7 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; @@ -1571,6 +1572,34 @@ declare namespace Ember { @return {Promise} */ finally(callback: (a: T) => V, label?: string): Promise; + + static all(promises: GlobalArray<(Q | Thenable)>): Promise; + static race(promises: GlobalArray>): Promise; + + /** + @method resolve + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + static resolve(object?: Q | Thenable): Promise; + + /** + @method cast (Deprecated in favor of resolve + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + static cast(object: Q | Thenable, label?: string): Promise; + + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + */ + static reject(reason?: any): Promise; } function all(promises: GlobalArray>): Promise; diff --git a/types/emscripten/emscripten-tests.ts b/types/emscripten/emscripten-tests.ts index 0c7f99b710..153ea6b5de 100644 --- a/types/emscripten/emscripten-tests.ts +++ b/types/emscripten/emscripten-tests.ts @@ -1,8 +1,20 @@ - - - /// Module function ModuleTest(): void { + Module.environment = "WEB"; + Module.environment = "NODE"; + Module.noInitialRun = false; + Module.logReadFiles = false; + Module.filePackagePrefixURL = "http://www.example.org/"; + Module.preinitializedWebGLContext = new WebGLRenderingContext(); + + let package: ArrayBuffer = Module.getPreloadedPackage("package-name", 100); + let exports: WebAssembly.Exports = Module.instantiateWasm( + [{name: "func-name", kind: "function"}], + (module: WebAssembly.Module) => {} + ); + let memFile: string = Module.locateFile("http://www.example.org/file.mem"); + Module.onCustomMessage(new MessageEvent("TestType")); + Module.print = function(text) { alert('stdout: ' + text) }; var int_sqrt = Module.cwrap('int_sqrt', 'number', ['number']) @@ -16,6 +28,7 @@ function ModuleTest(): void { Module.HEAPU8.set(myTypedArray, buf); Module.ccall('my_function', 'number', ['number'], [buf]); Module._free(buf); + Module.destroy({}); } /// FS diff --git a/types/emscripten/index.d.ts b/types/emscripten/index.d.ts index 38e659a0f3..14260dd9d4 100644 --- a/types/emscripten/index.d.ts +++ b/types/emscripten/index.d.ts @@ -1,7 +1,11 @@ // Type definitions for Emscripten // Project: http://kripken.github.io/emscripten-site/index.html // Definitions by: Kensuke Matsuzaki +// Periklis Tsirakidis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// declare namespace Emscripten { interface FileSystemType { @@ -9,13 +13,30 @@ declare namespace Emscripten { } declare namespace Module { + type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER"; + function print(str: string): void; function printErr(str: string): void; var arguments: string[]; + var environment: EnvironmentType; var preInit: { (): void }[]; var preRun: { (): void }[]; var postRun: { (): void }[]; + var preinitializedWebGLContext: WebGLRenderingContext; + var noInitialRun: boolean; var noExitRuntime: boolean; + var logReadFiles: boolean; + var filePackagePrefixURL: string; + var wasmBinary: ArrayBuffer; + + function destroy(object: object): void; + function getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer; + function instantiateWasm( + imports: WebAssembly.Imports, + successCallback: (module: WebAssembly.Module) => void + ): WebAssembly.Exports; + function locateFile(url: string): string; + function onCustomMessage(event: MessageEvent): void; var Runtime: any; @@ -65,7 +86,7 @@ declare namespace Module { function addOnExit(cb: () => any): void; function addOnPostRun(cb: () => any): void; - // Tools + // Tools function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[]; function intArrayToString(array: number[]): string; function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void; diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 7118fd4403..2dc9e98c87 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import {shallow, mount, render, ShallowWrapper, ReactWrapper} from "enzyme"; -import {Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent} from "react"; +import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces interface MyComponentProps { @@ -27,9 +27,11 @@ const MyStatelessComponent = (props: StatelessProps) => ; // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = - shallow(); + shallow(); let reactElement: ReactElement; + let reactElements: Array>; + let domElement: Element; let boolVal: boolean; let stringVal: string; let numOrStringVal: number | string; @@ -44,7 +46,7 @@ function ShallowWrapperTest() { } function test_shallow_options() { - shallow(, { + shallow(, { context: { test: "a", }, @@ -80,19 +82,19 @@ function ShallowWrapperTest() { } function test_contains() { - boolVal = shallowWrapper.contains(
); + boolVal = shallowWrapper.contains(
); } function test_containsMatchingElement() { - boolVal = shallowWrapper.contains(
); + boolVal = shallowWrapper.contains(
); } function test_containsAllMatchingElements() { - boolVal = shallowWrapper.containsAllMatchingElements([
]); + boolVal = shallowWrapper.containsAllMatchingElements([
]); } function test_containsAnyMatchingElement() { - boolVal = shallowWrapper.containsAnyMatchingElements([
]); + boolVal = shallowWrapper.containsAnyMatchingElements([
]); } function test_dive() { @@ -104,15 +106,15 @@ function ShallowWrapperTest() { bar: any; } - const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' }}); + const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' } }); } function test_equals() { - boolVal = shallowWrapper.equals(
); + boolVal = shallowWrapper.equals(
); } function test_matchesElement() { - boolVal = shallowWrapper.matchesElement(
); + boolVal = shallowWrapper.matchesElement(
); } function test_hasClass() { @@ -196,6 +198,18 @@ function ShallowWrapperTest() { reactElement = shallowWrapper.get(1); } + function test_getNode() { + reactElement = shallowWrapper.getNode(); + } + + function test_getNodes() { + reactElements = shallowWrapper.getNodes(); + } + + function test_getDOMNode() { + domElement = shallowWrapper.getDOMNode(); + } + function test_at() { shallowWrapper = shallowWrapper.at(1); } @@ -208,6 +222,15 @@ function ShallowWrapperTest() { shallowWrapper = shallowWrapper.last(); } + function test_slice() { + shallowWrapper = shallowWrapper.slice(1); + shallowWrapper = shallowWrapper.slice(1, 3); + } + + function test_tap() { + shallowWrapper.tap((intercepter) => { }); + } + function test_state() { const state: MyComponentState = shallowWrapper.state(); const prop: string = shallowWrapper.state('stateProperty'); @@ -333,9 +356,11 @@ function ShallowWrapperTest() { // ReactWrapper function ReactWrapperTest() { let reactWrapper: ReactWrapper = - mount(); + mount(); let reactElement: ReactElement; + let reactElements: Array>; + let domElement: Element; let boolVal: boolean; let stringVal: string; let elementWrapper: ReactWrapper, {}>; @@ -355,7 +380,7 @@ function ReactWrapperTest() { function test_mount() { reactWrapper = reactWrapper.mount(); - mount(, { + mount(, { attachTo: document.getElementById('test'), context: { a: "b" @@ -409,27 +434,27 @@ function ReactWrapperTest() { } function test_contains() { - boolVal = reactWrapper.contains(
); + boolVal = reactWrapper.contains(
); } function test_containsMatchingElement() { - boolVal = reactWrapper.contains(
); + boolVal = reactWrapper.contains(
); } function test_containsAllMatchingElements() { - boolVal = reactWrapper.containsAllMatchingElements([
]); + boolVal = reactWrapper.containsAllMatchingElements([
]); } function test_containsAnyMatchingElement() { - boolVal = reactWrapper.containsAnyMatchingElements([
]); + boolVal = reactWrapper.containsAnyMatchingElements([
]); } function test_equals() { - boolVal = reactWrapper.equals(
); + boolVal = reactWrapper.equals(
); } function test_matchesElement() { - boolVal = reactWrapper.matchesElement(
); + boolVal = reactWrapper.matchesElement(
); } function test_hasClass() { @@ -501,6 +526,18 @@ function ReactWrapperTest() { reactElement = reactWrapper.get(1); } + function test_getNode() { + reactElement = reactWrapper.getNode(); + } + + function test_getNodes() { + reactElements = reactWrapper.getNodes(); + } + + function test_getDOMNode() { + domElement = reactWrapper.getDOMNode(); + } + function test_at() { reactWrapper = reactWrapper.at(1); } @@ -513,6 +550,15 @@ function ReactWrapperTest() { reactWrapper = reactWrapper.last(); } + function test_slice() { + reactWrapper = reactWrapper.slice(1); + reactWrapper = reactWrapper.slice(1, 3); + } + + function test_tap() { + reactWrapper.tap((intercepter) => { }); + } + function test_state() { const state: MyComponentState = reactWrapper.state(); const prop: string = reactWrapper.state('stateProperty'); diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index abd40975be..721895e522 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme 2.7 +// Type definitions for Enzyme 2.8 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus // Cap3 @@ -6,6 +6,7 @@ // Tom Crockett // jwbay // huhuanming +// MartynasZilinskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -22,7 +23,7 @@ export class ElementClass extends Component { * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics */ export interface ComponentClass { - new(props?: Props, context?: any): Component; + new (props?: Props, context?: any): Component; } export type StatelessComponent = (props: Props, context?: any) => JSX.Element; @@ -42,6 +43,8 @@ export interface EnzymePropSelector { } export type EnzymeSelector = string | StatelessComponent | ComponentClass | EnzymePropSelector; +export type Intercepter = (intercepter: T) => void; + export interface CommonWrapper { /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. @@ -97,6 +100,7 @@ export interface CommonWrapper { /** * Returns whether or not the current node is empty. + * @deprecated Use .exists() instead. */ isEmpty(): boolean; @@ -134,6 +138,21 @@ export interface CommonWrapper { */ get(index: number): ReactElement; + /** + * Returns the wrapper's underlying node. + */ + getNode(): ReactElement; + + /** + * Returns the wrapper's underlying nodes. + */ + getNodes(): Array>; + + /** + * Returns the outer most DOMComponent of the current wrapper. + */ + getDOMNode(): Element; + /** * Returns a wrapper around the node at a given index of the current wrapper. * @param index @@ -150,6 +169,16 @@ export interface CommonWrapper { */ last(): this; + /** + * Returns a new wrapper with a subset of the nodes of the original wrapper, according to the rules of `Array#slice`. + */ + slice(begin?: number, end?: number): this; + + /** + * Taps into the wrapper method chain. Helpful for debugging. + */ + tap(intercepter: Intercepter): this; + /** * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. * @param [key] @@ -335,7 +364,7 @@ export interface CommonWrapper { * * Note: can only be called on a wrapper of a single node. */ - type(): string | ComponentClass

| StatelessComponent

; + type(): string | ComponentClass

| StatelessComponent

; length: number; } diff --git a/types/exceljs/exceljs-tests.ts b/types/exceljs/exceljs-tests.ts new file mode 100644 index 0000000000..95147c7726 --- /dev/null +++ b/types/exceljs/exceljs-tests.ts @@ -0,0 +1,82 @@ +import * as Excel from 'exceljs'; + +// most examples taken and adapted from README.md + +const workbook = new Excel.Workbook(); + +workbook.creator = 'Me'; +workbook.lastModifiedBy = 'Her'; +workbook.created = new Date(1985, 8, 30); +workbook.modified = new Date(); +workbook.lastPrinted = new Date(2016, 9, 27); +workbook.properties.date1904 = true; + +workbook.views = [ + { + x: 0, y: 0, width: 10000, height: 20000, + firstSheet: 0, activeTab: 1, visibility: 'visible' + } +]; + +const worksheet: Excel.Worksheet = workbook.addWorksheet('My Sheet'); +const worksheet2 = workbook.getWorksheet('My Sheet'); +const worksheet3 = workbook.getWorksheet(1); +const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); + +const row: Excel.Row = worksheet.addRow([3, 'Sam', new Date()]); +row.getCell(1).value = 5; + +worksheet.eachRow((row: Excel.Row, rowNumber: number): void => { + // nothing +}); + +row.eachCell((cell: Excel.Cell, colNumber: number): void => { + // nothing +}); + +worksheet.mergeCells('A4:B5'); + +worksheet.getCell('A1').numFmt = '0.00%'; +worksheet.getCell('A1').font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: true, + bold: true +}; + +worksheet.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; +worksheet.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; +worksheet.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; +worksheet.getCell('D1').alignment = { wrapText: true }; +worksheet.getCell('E1').alignment = { indent: 1 }; + +worksheet.getCell('A1').border = { + top: {style: 'thin'}, + left: {style: 'thin'}, + bottom: {style: 'thin'}, + right: {style: 'thin'} +}; + +worksheet.getCell('A3').border = { + top: {style: 'double', color: {argb: 'FF00FF00'}}, + left: {style: 'double', color: {argb: 'FF00FF00'}}, + bottom: {style: 'double', color: {argb: 'FF00FF00'}}, + right: {style: 'double', color: {argb: 'FF00FF00'}} +}; + +worksheet.getCell('A1').fill = { + type: 'pattern', + pattern: 'solid', + fgColor: {argb: 'FFFF0000'} +}; + +workbook.xlsx.readFile("/home/john/bla.xlsx") + .then((): void => { + // use workbook + }); + +workbook.xlsx.writeFile("/home/john/bla.xlsx") + .then((): void => { + // done + }); diff --git a/types/exceljs/index.d.ts b/types/exceljs/index.d.ts new file mode 100644 index 0000000000..259eaccae1 --- /dev/null +++ b/types/exceljs/index.d.ts @@ -0,0 +1,231 @@ +// Type definitions for exceljs 0.4 +// Project: https://github.com/guyonroche/exceljs +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const enum ValueType { + Null = 0, + Merge = 1, + Number = 2, + String = 3, + Date = 4, + Hyperlink = 5, + Formula = 6, + SharedString = 7, + RichText = 8, + Boolean = 9, + Error = 10 +} + +export const enum FormulaType { + None = 0, + Master = 1, + Shared = 2 +} + +export const enum RelationshipType { + None = 0, + OfficeDocument = 1, + Worksheet = 2, + CalcChain = 3, + SharedStrings = 4, + Styles = 5, + Theme = 6, + Hyperlink = 7 +} + +export const enum DocumentType { + Xlsx = 1 +} + +export const enum ReadingOrder { + RightToLeft = 1, + LeftToRight = 2, +} + +export interface ErrorValue { + error: "#N/A" | "#REF!" | "#NAME?" | "#DIV/0!" | "#NULL!" | "#VALUE!" | "#NUM!"; +} + +export interface WorksheetView { + state?: "normal" | "split" | "frozen"; + showRuler?: boolean; + showRowColHeaders?: boolean; + showGridLines?: boolean; + zoomScale?: number; + zoomScaleNormal?: number; + style?: "pageBreakPreview" | "pageLayout"; +} + +export interface WorkbookView { + x?: number; + y?: number; + width?: number; + height?: number; + firstSheet?: number; + activeTab?: number; + visibility?: string; +} + +export interface Fill { + type: "pattern" | "gradient"; + pattern?: "none" | "solid"; + fgColor?: Color; + bgColor?: Color; +} + +export interface Font { + name: string; + size?: number; + family?: number; + schema?: "minor" | "major" | "none"; + charset?: number; + color?: Color; + bold?: boolean; + italic?: boolean; + underline?: true | false | "none" | "single" | "double" | "singleAccounting" | "doubleAccounting"; + strike?: boolean; + outline?: boolean; +} + +export type BorderStyle = + "thin" | "dotted" | "dashDot" | "hair" | "dashDotDot" | "slantDashDot" | "mediumDashed" | "mediumDashDotDot" | + "mediumDashDot" | "medium" | "double" | "thick"; + +export interface Color { + /** + * Hex string for alpha-red-green-blue e.g. FF00FF00 + */ + argb: string; +} + +export interface Border { + style?: BorderStyle; + color?: Color; +} + +export interface Borders { + top?: Border; + left?: Border; + bottom?: Border; + right?: Border; +} + +export interface Alignment { + horizontal?: "left" | "center" | "right" | "fill" | "justify" | "centerContinuous" | "distributed"; + vertical?: "top" | "middle" | "bottom" | "distributed" | "justify"; + wrapText?: boolean; + indent?: number; + readingOrder?: "rtl" | "ltr"; + textrotation?: number | "vertical"; +} + +export interface Cell { + border?: Borders; + font?: Font; + alignment?: Alignment; + numFmt?: string; + value?: any; + fill?: Fill; +} + +export interface Row { + /** + * The row number + */ + number: number; + height: number; + hidden: boolean; + collapsed: boolean; + values: any[]; + outlineLevel?: number; + + readonly cellCount: number; + readonly actualCellCount: number; + + getCell(index: number): Cell; + + eachCell(callback: (cell: Cell, colNumber: number) => void): void; + eachCell(opts: { includeEmpty: boolean}, callback: (cell: Cell, colNumber: number) => void): void; +} + +export interface Column { + width: number; +} + +export interface Worksheet { + /** + * The total row size of the document. Equal to the row number of the last row that has values. + */ + rowCount: number; + /** + * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. + */ + actualRowCount: number; + /** + * The total column size of the document. Equal to the maximum cell count from all of the rows + */ + columnCount: number; + /** + * A count of the number of columns that have values. + */ + actualColumnCount: number; + + /** + * Get or create a column + */ + getColumn(index: number): Column; + + /** + * Create a new row + */ + addRow(data: any[]): Row; + + /** + * Get or create row by 0-based index + */ + getRow(index: number): Row; + eachRow(callback: (row: Row, rowNumber: number) => void): void; + + /** + * Get or create cell + */ + getCell(ref: string): Cell; + + /** + * Merge cells, either: + * tlbr string + * tl string, br string + * t, l, b, r numbers + */ + mergeCells(a: number | string, b?: number | string, c?: number, d?: number): void; +} + +export interface Xlsx { + readFile(path: string): Promise; + writeFile(path: string): Promise; +} + +export interface WorksheetProps { + showGridLines: boolean; +} + +export class Workbook { + constructor(); + + creator: string; + lastModifiedBy: string; + created: Date; + modified: Date; + lastPrinted: Date; + properties: { + date1904: boolean; + }; + views: WorkbookView[]; + + addWorksheet(name: string, opts?: { properties?: WorksheetProps, views?: WorksheetView[] }): Worksheet; + + getWorksheet(indexOrName: number | string): Worksheet; + + xlsx: Xlsx; +} diff --git a/types/exceljs/tsconfig.json b/types/exceljs/tsconfig.json new file mode 100644 index 0000000000..f9cb219d06 --- /dev/null +++ b/types/exceljs/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "exceljs-tests.ts" + ] +} diff --git a/types/exceljs/tslint.json b/types/exceljs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/exceljs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fabric/fabric-tests.ts b/types/fabric/fabric-tests.ts index 62c0726e16..770467590c 100644 --- a/types/fabric/fabric-tests.ts +++ b/types/fabric/fabric-tests.ts @@ -1,5 +1,3 @@ -import * as fabric from "fabric"; - function sample1() { const canvas = new fabric.Canvas('c', { hoverCursor: 'pointer', @@ -124,11 +122,12 @@ function sample3() { } }); - fabric.Image.fromURL('../assets/printio.png', img => { + const image = fabric.Image.fromURL('../assets/printio.png', img => { const oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); canvas.add(oImg).renderAll(); canvas.setActiveObject(oImg); }); + image.setSrc('../assets/printio.png'); $('grayscale').onclick = function(this: HTMLInputElement) { applyFilter(0, this.checked && new f.Grayscale()); @@ -260,18 +259,18 @@ function sample4() { }); } -declare module "fabric" { - export interface CircleWithLineInfos extends Circle { - line1?: Line; - line2?: Line; - line3?: Line; - line4?: Line; +namespace myfabric { + export interface CircleWithLineInfos extends fabric.Circle { + line1?: fabric.Line; + line2?: fabric.Line; + line3?: fabric.Line; + line4?: fabric.Line; } } function sample5() { const makeCircle = (left: number, top: number, line1?: fabric.Line, line2?: fabric.Line, line3?: fabric.Line, line4?: fabric.Line): fabric.Circle => { - const c = new fabric.Circle({ + const c = new fabric.Circle({ left, top, strokeWidth: 5, @@ -318,7 +317,7 @@ function sample5() { ); canvas.on('object:moving', e => { - const p = e.target; + const p = e.target; p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); @@ -352,8 +351,8 @@ function sample6() { }); } -declare module "fabric" { - export interface ImageWithInfo extends Image { +namespace myfabric { + export interface ImageWithInfo extends fabric.Image { movingLeft: boolean; } } @@ -363,7 +362,7 @@ function sample7() { setInterval(() => { fabric.Image.fromURL('../assets/ladybug.png', obj => { - const img = obj; + const img = obj; img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); img.movingLeft = !!Math.round(Math.random()); canvas.add(img); @@ -372,7 +371,7 @@ function sample7() { const animate = (function animate() { canvas.forEachObject(obj => { - const img = obj; + const img = obj; img.left += (img.movingLeft ? -1 : 1); img.top += 1; if (img.left > 900 || img.top > 500) { @@ -609,7 +608,7 @@ function sample8() { const activeGroup = canvas.getActiveGroup(); if (activeObject || activeGroup) { - (activeObject || activeGroup).setOpacity(parseInt(this.value, 10) / 100); + (activeObject || activeGroup).setOpacity(parseInt(( this).value, 10) / 100); canvas.renderAll(); } }; @@ -640,7 +639,7 @@ function sample8() { const activeGroup = canvas.getActiveGroup(); if (activeObject || activeGroup) { - (activeObject || activeGroup).setFill(this.value); + (activeObject || activeGroup).setFill(( this).value); canvas.renderAll(); } }; @@ -849,16 +848,16 @@ function sample8() { const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - this.value = ( activeObject).text; + ( this).value = ( activeObject).text; } }; textEl.onkeyup = function(e) { const activeObject = canvas.getActiveObject(); if (activeObject) { - if (!this.value) { + if (!( this).value) { canvas.discardActiveObject(); } else { - ( activeObject).text = this.value; + ( activeObject).text = ( this).value; } canvas.renderAll(); } @@ -1006,7 +1005,7 @@ function sample8() { slider.onchange = function() { const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.lineHeight = +this.value; + activeObject.lineHeight = +( this).value; canvas.renderAll(); } }; diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index ca99080bad..1596d7d428 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -1866,7 +1866,7 @@ export class Image { * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied) * @param {Object} [options] Options object */ - setSrc(src: string, callback: Function, options: IImageOptions): Image; + setSrc(src: string, callback?: Function, options?: IImageOptions): Image; /** * Creates an instance of fabric.Image from an URL string diff --git a/types/fecha/fecha-tests.ts b/types/fecha/fecha-tests.ts new file mode 100644 index 0000000000..0d0ce48638 --- /dev/null +++ b/types/fecha/fecha-tests.ts @@ -0,0 +1,124 @@ +import fecha = require('fecha'); + +// test fecha.parse +fecha.parse("February 3rd, 2014", "MMMM Do, YYYY"); +fecha.parse("5/3/98", "shortDate"); + +// test override fecha.i18n +fecha.i18n = { + dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"], + dayNames: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + monthNamesShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + monthNames: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + amPm: ["am", "pm"], + DoFn(D: number) { + return D + "th"; + } +}; + +// just change one default mask +fecha.masks.shortDate = "M/D/YY"; + +// test override fecha.masks with an object. Must implement all keys. +// if you want to implement partially, use +// fecha.masks = Object.assign(fecha.masks, {shortDate: 'M/D/YY'}) for example. +fecha.masks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; + +// test add custom named mask. +// fecha.masks.myMask = "HH:mm:ss YY/MM/DD"; does not work for now. +fecha.masks['myMask'] = "HH:mm:ss YY/MM/DD"; + +// test fecha.format without i18nSettings, with Date object. +fecha.format(new Date(2014, 5, 6, 14, 10, 45), "myMask"); + +// test fecha.format without i18nSettings with number. +fecha.format(Date.now(), "myMask"); + +// test override i18nSettings with fecha.format +fecha.format(new Date(2014, 5, 6, 14, 10, 45), "myMask", { + dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"], + dayNames: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + monthNamesShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + monthNames: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + amPm: ["am", "pm"], + DoFn(D: number) { + return D + "th"; + } +}); diff --git a/types/fecha/index.d.ts b/types/fecha/index.d.ts new file mode 100644 index 0000000000..f68d26a316 --- /dev/null +++ b/types/fecha/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for fecha 2.3 +// Project: https://github.com/taylorhakes/fecha +// Definitions by: Goh Yisheng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Days = [string, string, string, string, string, string, string]; + +export type Months = [ + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string +]; + +export interface i18nSettings { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(D: number): string; +} + +export interface Masks { + default: string; + fullDate: string; + longDate: string; + longTime: string; + mediumDate: string; + mediumTime: string; + shortDate: string; + shortTime: string; + [myMask: string]: string; +} + +export let masks: Masks; + +export let i18n: i18nSettings; + +export function format(dateObj: Date | number, mask: string, i18nSettings?: i18nSettings): string; + +export function parse(dateStr: string, format: string, i18nSettings?: i18nSettings): Date; + +export as namespace Fecha; diff --git a/types/fecha/tsconfig.json b/types/fecha/tsconfig.json new file mode 100644 index 0000000000..581630d1b6 --- /dev/null +++ b/types/fecha/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fecha-tests.ts" + ] +} diff --git a/types/fecha/tslint.json b/types/fecha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fecha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/file-saver/file-saver-tests.ts b/types/file-saver/file-saver-tests.ts index aefc9dca7f..c76815a6fb 100644 --- a/types/file-saver/file-saver-tests.ts +++ b/types/file-saver/file-saver-tests.ts @@ -19,3 +19,12 @@ function testSaveAs() { saveAs(data, filename, disableAutoBOM); } + +/** + * @summary Test for "saveAs" function. + */ +function testSaveAsFile() { + const data = new File(["Hello, world!"], "hello world.txt" ,{type: "text/plain;charset=utf-8"}); + + saveAs(data); +} diff --git a/types/file-saver/index.d.ts b/types/file-saver/index.d.ts index 31188a0c7a..8d78e10682 100644 --- a/types/file-saver/index.d.ts +++ b/types/file-saver/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for FileSaver.js // Project: https://github.com/eligrey/FileSaver.js/ -// Definitions by: Cyril Schumacher +// Definitions by: Cyril Schumacher , Daniel Roth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -28,6 +28,14 @@ interface FileSaver { */ disableAutoBOM?: boolean ): void + + ( + /** + * @summary File. + * @type {File} + */ + data: File + ): void } declare var saveAs: FileSaver; diff --git a/types/firmata/index.d.ts b/types/firmata/index.d.ts index f18294d110..8f0457d46e 100644 --- a/types/firmata/index.d.ts +++ b/types/firmata/index.d.ts @@ -259,7 +259,7 @@ declare namespace Board { } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L449-L464 - enum PIN_MODE { + const enum PIN_MODE { INPUT = 0x00, OUTPUT = 0x01, ANALOG = 0x02, @@ -276,30 +276,30 @@ declare namespace Board { UNKNOWN = 0x10, } - enum PIN_STATE { + const enum PIN_STATE { LOW = 0, HIGH = 1 } - enum REPORTING { + const enum REPORTING { ON = 1, OFF = 0, } - enum PULLUP_STATE { + const enum PULLUP_STATE { ENABLED = 1, DISABLED = 0, } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L474-L478 - enum STEPPER_TYPE { + const enum STEPPER_TYPE { DRIVER = 1, TWO_WIRE = 2, FOUR_WIRE = 4, } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L479-L484 - enum STEPPER_RUN_STATE { + const enum STEPPER_RUN_STATE { STOP = 0, ACCEL = 1, DECEL = 2, @@ -307,13 +307,13 @@ declare namespace Board { } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L485-L488 - enum STEPPER_DIRECTION { + const enum STEPPER_DIRECTION { CCW = 0, CW = 1, } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L466-L471 - enum I2C_MODE { + const enum I2C_MODE { WRITE = 0, READ = 1, CONTINUOUS_READ = 2, @@ -321,13 +321,13 @@ declare namespace Board { } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L491-L494 - enum SERIAL_MODE { + const enum SERIAL_MODE { CONTINUOUS_READ = 0x00, STOP_READING = 0x01, } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L497-L512 - enum SERIAL_PORT_ID { + const enum SERIAL_PORT_ID { HW_SERIAL0 = 0x00, HW_SERIAL1 = 0x01, HW_SERIAL2 = 0x02, @@ -340,7 +340,7 @@ declare namespace Board { } // https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L515-L524 - enum SERIAL_PIN_TYPE { + const enum SERIAL_PIN_TYPE { RES_RX0 = 0x00, RES_TX0 = 0x01, RES_RX1 = 0x02, diff --git a/types/fixed-data-table/fixed-data-table-tests.tsx b/types/fixed-data-table/fixed-data-table-tests.tsx index f57ff3d946..64b622b21f 100644 --- a/types/fixed-data-table/fixed-data-table-tests.tsx +++ b/types/fixed-data-table/fixed-data-table-tests.tsx @@ -93,7 +93,11 @@ class MyTextCell extends React.Component { const {rowIndex, field, myData} = this.props; return ( - + {myData[rowIndex][field]} ); @@ -106,7 +110,11 @@ class MyLinkCell extends React.Component { const link: string = myData[rowIndex][field]; return ( - + {link} ); diff --git a/types/fluent-ffmpeg/fluent-ffmpeg-tests.ts b/types/fluent-ffmpeg/fluent-ffmpeg-tests.ts index 112d6de09b..b4beb14ef7 100644 --- a/types/fluent-ffmpeg/fluent-ffmpeg-tests.ts +++ b/types/fluent-ffmpeg/fluent-ffmpeg-tests.ts @@ -1,5 +1,7 @@ -import ffmpeg = require("fluent-ffmpeg") +import * as ffmpeg from "fluent-ffmpeg"; -let source: string, format: string, output: string +let source: string; +let format: string; +let output: string; -ffmpeg({ source: source }).format(format).save(output) +ffmpeg({ source }).format(format).save(output); diff --git a/types/fluent-ffmpeg/index.d.ts b/types/fluent-ffmpeg/index.d.ts index 538ac71761..1e44422789 100644 --- a/types/fluent-ffmpeg/index.d.ts +++ b/types/fluent-ffmpeg/index.d.ts @@ -1,315 +1,304 @@ -// Type definitions for node-fluent-ffmpeg +// Type definitions for node-fluent-ffmpeg 2.1 // Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg -// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk , DingWeizhe // Definitions: https://github.com/DefinitelyType/DefinitelyTyped /// -declare module "fluent-ffmpeg" { - import * as events from "events" - import * as stream from "stream" +import * as events from "events"; +import * as stream from "stream"; +declare namespace Ffmpeg { interface FfmpegCommandLogger { - error(...data: any[]): void - warning(...data: any[]): void - info(...data: any[]): void - debug(...data: any[]): void + error(...data: any[]): void; + warning(...data: any[]): void; + info(...data: any[]): void; + debug(...data: any[]): void; } interface FfmpegCommandOptions { - logger?: FfmpegCommandLogger - niceness?: number - priority?: number - presets?: string - preset?: string - stdoutLines?: number - timeout?: number - source?: string | stream.Readable + logger?: FfmpegCommandLogger; + niceness?: number; + priority?: number; + presets?: string; + preset?: string; + stdoutLines?: number; + timeout?: number; + source?: string | stream.Readable; } interface FilterSpecification { - filter: string - inputs: string | string[] - outputs: string | string[] - options?: Object | string | any[] + filter: string; + inputs: string | string[]; + outputs: string | string[]; + options?: any | string | any[]; } - interface GetPreset { - (command: FfmpegCommand): string - } + type GetPreset = (command: FfmpegCommand) => string; interface Filter { - description: string - input: string - multipleInputs: boolean - output: string - multipleOutputs: boolean + description: string; + input: string; + multipleInputs: boolean; + output: string; + multipleOutputs: boolean; } interface Filters { - [key: string]: Filter - } - interface FiltersCallback { - (err: Error, filters: Filters): void + [key: string]: Filter; } + type FiltersCallback = (err: Error, filters: Filters) => void; interface Codec { - type: string - description: string - canDecode: boolean - canEncode: boolean - drawHorizBand?: boolean - directRendering?: boolean - weirdFrameTruncation?: boolean - intraFrameOnly?: boolean - isLossy?: boolean - isLossless?: boolean + type: string; + description: string; + canDecode: boolean; + canEncode: boolean; + drawHorizBand?: boolean; + directRendering?: boolean; + weirdFrameTruncation?: boolean; + intraFrameOnly?: boolean; + isLossy?: boolean; + isLossless?: boolean; } interface Codecs { - [key: string]: Codec - } - interface CodecsCallback { - (err: Error, codecs: Codecs): void + [key: string]: Codec; } + type CodecsCallback = (err: Error, codecs: Codecs) => void; interface Encoder { - type: string - description: string - frameMT: boolean - sliceMT: boolean - experimental: boolean - drawHorizBand: boolean - directRendering: boolean + type: string; + description: string; + frameMT: boolean; + sliceMT: boolean; + experimental: boolean; + drawHorizBand: boolean; + directRendering: boolean; } interface Encoders { - [key: string]: Encoder - } - interface EncodersCallback { - (err: Error, encoders: Encoders): void + [key: string]: Encoder; } + type EncodersCallback = (err: Error, encoders: Encoders) => void; interface Format { - description: string - canDemux: boolean - canMux: boolean + description: string; + canDemux: boolean; + canMux: boolean; } interface Formats { - [key: string]: Format - } - interface FormatsCallback { - (err: Error, formats: Formats): void + [key: string]: Format; } + type FormatsCallback = (err: Error, formats: Formats) => void; interface FfprobeData { - stream: any[] - format: any - chapters: any[] + stream: any[]; + format: any; + chapters: any[]; } interface ScreenshotsConfig { - count?: number - folder?: string - filename?: string - timemarks?: number[] | string[] - timestamps?: number[] | string[] - fastSeek?: boolean - size?: string + count?: number; + folder?: string; + filename?: string; + timemarks?: number[] | string[]; + timestamps?: number[] | string[]; + fastSeek?: boolean; + size?: string; } - interface FfmpegCommand extends events.EventEmitter { - constructor(): FfmpegCommand - constructor(options: FfmpegCommandOptions): FfmpegCommand - constructor(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand + class FfmpegCommand extends events.EventEmitter { + constructor(options?: FfmpegCommandOptions); + constructor(input?: string | stream.Readable, options?: FfmpegCommandOptions); // options/inputs - mergeAdd(source: string | stream.Readable): FfmpegCommand - addInput(source: string | stream.Readable): FfmpegCommand - input(source: string | stream.Readable): FfmpegCommand - withInputFormat(format: string): FfmpegCommand - inputFormat(format: string): FfmpegCommand - fromFormat(format: string): FfmpegCommand - withInputFps(fps: number): FfmpegCommand - withInputFPS(fps: number): FfmpegCommand - withFpsInput(fps: number): FfmpegCommand - withFPSInput(fps: number): FfmpegCommand - inputFPS(fps: number): FfmpegCommand - inputFps(fps: number): FfmpegCommand - fpsInput(fps: number): FfmpegCommand - FPSInput(fps: number): FfmpegCommand - nativeFramerate(): FfmpegCommand - withNativeFramerate(): FfmpegCommand - native(): FfmpegCommand - setStartTime(seek: string | number): FfmpegCommand - seekInput(seek: string | number): FfmpegCommand - loop(duration: string | number): FfmpegCommand + mergeAdd(source: string | stream.Readable): FfmpegCommand; + addInput(source: string | stream.Readable): FfmpegCommand; + input(source: string | stream.Readable): FfmpegCommand; + withInputFormat(format: string): FfmpegCommand; + inputFormat(format: string): FfmpegCommand; + fromFormat(format: string): FfmpegCommand; + withInputFps(fps: number): FfmpegCommand; + withInputFPS(fps: number): FfmpegCommand; + withFpsInput(fps: number): FfmpegCommand; + withFPSInput(fps: number): FfmpegCommand; + inputFPS(fps: number): FfmpegCommand; + inputFps(fps: number): FfmpegCommand; + fpsInput(fps: number): FfmpegCommand; + FPSInput(fps: number): FfmpegCommand; + nativeFramerate(): FfmpegCommand; + withNativeFramerate(): FfmpegCommand; + native(): FfmpegCommand; + setStartTime(seek: string | number): FfmpegCommand; + seekInput(seek: string | number): FfmpegCommand; + loop(duration: string | number): FfmpegCommand; // options/audio - withNoAudio(): FfmpegCommand - noAudio(): FfmpegCommand - withAudioCodec(codec: string): FfmpegCommand - audioCodec(codec: string): FfmpegCommand - withAudioBitrate(bitrate: string | number): FfmpegCommand - audioBitrate(bitrate: string | number): FfmpegCommand - withAudioChannels(channels: number): FfmpegCommand - audioChannels(channels: number): FfmpegCommand - withAudioFrequency(freq: number): FfmpegCommand - audioFrequency(freq: number): FfmpegCommand - withAudioQuality(quality: number): FfmpegCommand - audioQuality(quality: number): FfmpegCommand - withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand - withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand - audioFilter(filters: { filter: string, options: any }): FfmpegCommand - audioFilters(filters: { filter: string, options: any }): FfmpegCommand + withNoAudio(): FfmpegCommand; + noAudio(): FfmpegCommand; + withAudioCodec(codec: string): FfmpegCommand; + audioCodec(codec: string): FfmpegCommand; + withAudioBitrate(bitrate: string | number): FfmpegCommand; + audioBitrate(bitrate: string | number): FfmpegCommand; + withAudioChannels(channels: number): FfmpegCommand; + audioChannels(channels: number): FfmpegCommand; + withAudioFrequency(freq: number): FfmpegCommand; + audioFrequency(freq: number): FfmpegCommand; + withAudioQuality(quality: number): FfmpegCommand; + audioQuality(quality: number): FfmpegCommand; + withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand; + withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand; + audioFilter(filters: { filter: string, options: any }): FfmpegCommand; + audioFilters(filters: { filter: string, options: any }): FfmpegCommand; - // options/video - withNoVideo(): FfmpegCommand - noVideo(): FfmpegCommand - withVideoCodec(codec: string): FfmpegCommand - videoCodec(codec: string): FfmpegCommand - withVideoBitrate(bitrate: string | number): FfmpegCommand - videoBitrate(bitrate: string | number): FfmpegCommand - withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand - withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand - videoFilter(filters: { filter: string, options: any }): FfmpegCommand - videoFilters(filters: { filter: string, options: any }): FfmpegCommand - withOutputFps(fps: number): FfmpegCommand - withOutputFPS(fps: number): FfmpegCommand - withFpsOutput(fps: number): FfmpegCommand - withFPSOutput(fps: number): FfmpegCommand - withFps(fps: number): FfmpegCommand - withFPS(fps: number): FfmpegCommand - outputFPS(fps: number): FfmpegCommand - outputFps(fps: number): FfmpegCommand - fpsOutput(fps: number): FfmpegCommand - FPSOutput(fps: number): FfmpegCommand - fps(fps: number): FfmpegCommand - FPS(fps: number): FfmpegCommand - takeFrames(frames: number): FfmpegCommand - withFrames(frames: number): FfmpegCommand - frames(frames: number): FfmpegCommand + // options/video; + withNoVideo(): FfmpegCommand; + noVideo(): FfmpegCommand; + withVideoCodec(codec: string): FfmpegCommand; + videoCodec(codec: string): FfmpegCommand; + withVideoBitrate(bitrate: string | number): FfmpegCommand; + videoBitrate(bitrate: string | number): FfmpegCommand; + withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand; + withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand; + videoFilter(filters: { filter: string, options: any }): FfmpegCommand; + videoFilters(filters: { filter: string, options: any }): FfmpegCommand; + withOutputFps(fps: number): FfmpegCommand; + withOutputFPS(fps: number): FfmpegCommand; + withFpsOutput(fps: number): FfmpegCommand; + withFPSOutput(fps: number): FfmpegCommand; + withFps(fps: number): FfmpegCommand; + withFPS(fps: number): FfmpegCommand; + outputFPS(fps: number): FfmpegCommand; + outputFps(fps: number): FfmpegCommand; + fpsOutput(fps: number): FfmpegCommand; + FPSOutput(fps: number): FfmpegCommand; + fps(fps: number): FfmpegCommand; + FPS(fps: number): FfmpegCommand; + takeFrames(frames: number): FfmpegCommand; + withFrames(frames: number): FfmpegCommand; + frames(frames: number): FfmpegCommand; // options/videosize - keepPixelAspect(): FfmpegCommand - keepDisplayAspect(): FfmpegCommand - keepDisplayAspectRatio(): FfmpegCommand - keepDAR(): FfmpegCommand - withSize(size: string): FfmpegCommand - setSize(size: string): FfmpegCommand - size(size: string): FfmpegCommand - withAspect(aspect: string | number): FfmpegCommand - withAspectRatio(aspect: string | number): FfmpegCommand - setAspect(aspect: string | number): FfmpegCommand - setAspectRatio(aspect: string | number): FfmpegCommand - aspect(aspect: string | number): FfmpegCommand - aspectRatio(aspect: string | number): FfmpegCommand - applyAutopadding(pad: boolean, color: string): FfmpegCommand - applyAutoPadding(pad: boolean, color: string): FfmpegCommand - applyAutopad(pad: boolean, color: string): FfmpegCommand - applyAutoPad(pad: boolean, color: string): FfmpegCommand - withAutopadding(pad: boolean, color: string): FfmpegCommand - withAutoPadding(pad: boolean, color: string): FfmpegCommand - withAutopad(pad: boolean, color: string): FfmpegCommand - withAutoPad(pad: boolean, color: string): FfmpegCommand - autoPad(pad: boolean, color: string): FfmpegCommand - autopad(pad: boolean, color: string): FfmpegCommand + keepPixelAspect(): FfmpegCommand; + keepDisplayAspect(): FfmpegCommand; + keepDisplayAspectRatio(): FfmpegCommand; + keepDAR(): FfmpegCommand; + withSize(size: string): FfmpegCommand; + setSize(size: string): FfmpegCommand; + size(size: string): FfmpegCommand; + withAspect(aspect: string | number): FfmpegCommand; + withAspectRatio(aspect: string | number): FfmpegCommand; + setAspect(aspect: string | number): FfmpegCommand; + setAspectRatio(aspect: string | number): FfmpegCommand; + aspect(aspect: string | number): FfmpegCommand; + aspectRatio(aspect: string | number): FfmpegCommand; + applyAutopadding(pad: boolean, color: string): FfmpegCommand; + applyAutoPadding(pad: boolean, color: string): FfmpegCommand; + applyAutopad(pad: boolean, color: string): FfmpegCommand; + applyAutoPad(pad: boolean, color: string): FfmpegCommand; + withAutopadding(pad: boolean, color: string): FfmpegCommand; + withAutoPadding(pad: boolean, color: string): FfmpegCommand; + withAutopad(pad: boolean, color: string): FfmpegCommand; + withAutoPad(pad: boolean, color: string): FfmpegCommand; + autoPad(pad: boolean, color: string): FfmpegCommand; + autopad(pad: boolean, color: string): FfmpegCommand; // options/output - addOutput(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand - output(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand - seekOutput(seek: string | number): FfmpegCommand - seek(seek: string | number): FfmpegCommand - withDuration(duration: string | number): FfmpegCommand - setDuration(duration: string | number): FfmpegCommand - duration(duration: string | number): FfmpegCommand - toFormat(format: string): FfmpegCommand - withOutputFormat(format: string): FfmpegCommand - outputFormat(format: string): FfmpegCommand - format(format: string): FfmpegCommand - map(spec: string): FfmpegCommand - updateFlvMetadata(): FfmpegCommand - flvmeta(): FfmpegCommand + addOutput(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand; + output(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand; + seekOutput(seek: string | number): FfmpegCommand; + seek(seek: string | number): FfmpegCommand; + withDuration(duration: string | number): FfmpegCommand; + setDuration(duration: string | number): FfmpegCommand; + duration(duration: string | number): FfmpegCommand; + toFormat(format: string): FfmpegCommand; + withOutputFormat(format: string): FfmpegCommand; + outputFormat(format: string): FfmpegCommand; + format(format: string): FfmpegCommand; + map(spec: string): FfmpegCommand; + updateFlvMetadata(): FfmpegCommand; + flvmeta(): FfmpegCommand; // options/custom - addInputOption(options: string[]): FfmpegCommand - addInputOption(...options: string[]): FfmpegCommand - addInputOptions(options: string[]): FfmpegCommand - addInputOptions(...options: string[]): FfmpegCommand - withInputOption(options: string[]): FfmpegCommand - withInputOption(...options: string[]): FfmpegCommand - withInputOptions(options: string[]): FfmpegCommand - withInputOptions(...options: string[]): FfmpegCommand - inputOption(options: string[]): FfmpegCommand - inputOption(...options: string[]): FfmpegCommand - inputOptions(options: string[]): FfmpegCommand - inputOptions(...options: string[]): FfmpegCommand - addOutputOption(options: string[]): FfmpegCommand - addOutputOption(...options: string[]): FfmpegCommand - addOutputOptions(options: string[]): FfmpegCommand - addOutputOptions(...options: string[]): FfmpegCommand - addOption(options: string[]): FfmpegCommand - addOption(...options: string[]): FfmpegCommand - addOptions(options: string[]): FfmpegCommand - addOptions(...options: string[]): FfmpegCommand - withOutputOption(options: string[]): FfmpegCommand - withOutputOption(...options: string[]): FfmpegCommand - withOutputOptions(options: string[]): FfmpegCommand - withOutputOptions(...options: string[]): FfmpegCommand - withOption(options: string[]): FfmpegCommand - withOption(...options: string[]): FfmpegCommand - withOptions(options: string[]): FfmpegCommand - withOptions(...options: string[]): FfmpegCommand - outputOption(options: string[]): FfmpegCommand - outputOption(...options: string[]): FfmpegCommand - outputOptions(options: string[]): FfmpegCommand - outputOptions(...options: string[]): FfmpegCommand - filterGraph(spec: string | FilterSpecification[], map: string[]): FfmpegCommand - complexFilter(spec: string | FilterSpecification[], map: string[]): FfmpegCommand + addInputOption(options: string[]): FfmpegCommand; + addInputOption(...options: string[]): FfmpegCommand; + addInputOptions(options: string[]): FfmpegCommand; + addInputOptions(...options: string[]): FfmpegCommand; + withInputOption(options: string[]): FfmpegCommand; + withInputOption(...options: string[]): FfmpegCommand; + withInputOptions(options: string[]): FfmpegCommand; + withInputOptions(...options: string[]): FfmpegCommand; + inputOption(options: string[]): FfmpegCommand; + inputOption(...options: string[]): FfmpegCommand; + inputOptions(options: string[]): FfmpegCommand; + inputOptions(...options: string[]): FfmpegCommand; + addOutputOption(options: string[]): FfmpegCommand; + addOutputOption(...options: string[]): FfmpegCommand; + addOutputOptions(options: string[]): FfmpegCommand; + addOutputOptions(...options: string[]): FfmpegCommand; + addOption(options: string[]): FfmpegCommand; + addOption(...options: string[]): FfmpegCommand; + addOptions(options: string[]): FfmpegCommand; + addOptions(...options: string[]): FfmpegCommand; + withOutputOption(options: string[]): FfmpegCommand; + withOutputOption(...options: string[]): FfmpegCommand; + withOutputOptions(options: string[]): FfmpegCommand; + withOutputOptions(...options: string[]): FfmpegCommand; + withOption(options: string[]): FfmpegCommand; + withOption(...options: string[]): FfmpegCommand; + withOptions(options: string[]): FfmpegCommand; + withOptions(...options: string[]): FfmpegCommand; + outputOption(options: string[]): FfmpegCommand; + outputOption(...options: string[]): FfmpegCommand; + outputOptions(options: string[]): FfmpegCommand; + outputOptions(...options: string[]): FfmpegCommand; + filterGraph(spec: string | FilterSpecification[], map: string[]): FfmpegCommand; + complexFilter(spec: string | FilterSpecification[], map: string[]): FfmpegCommand; // options/misc - usingPreset(proset: string | GetPreset): FfmpegCommand - pnreset(proset: string | GetPreset): FfmpegCommand + usingPreset(proset: string | GetPreset): FfmpegCommand; + pnreset(proset: string | GetPreset): FfmpegCommand; // processor - renice(niceness: number): FfmpegCommand - kill(signal: string): FfmpegCommand + renice(niceness: number): FfmpegCommand; + kill(signal: string): FfmpegCommand; // capabilities - setFfmpegPath(path: string): FfmpegCommand - setFfprobePath(path: string): FfmpegCommand - setFlvtoolPath(path: string): FfmpegCommand - availableFilters(callback: FiltersCallback): void - getAvailableFilters(callback: FiltersCallback): void - availableCodecs(callback: CodecsCallback): void - getAvailableCodecs(callback: CodecsCallback): void - availableEncoders(callback: EncodersCallback): void - getAvailableEncoders(callback: EncodersCallback): void - availableFormats(callback: FormatsCallback): void - getAvailableFormats(callback: FormatsCallback): void + setFfmpegPath(path: string): FfmpegCommand; + setFfprobePath(path: string): FfmpegCommand; + setFlvtoolPath(path: string): FfmpegCommand; + availableFilters(callback: FiltersCallback): void; + getAvailableFilters(callback: FiltersCallback): void; + availableCodecs(callback: CodecsCallback): void; + getAvailableCodecs(callback: CodecsCallback): void; + availableEncoders(callback: EncodersCallback): void; + getAvailableEncoders(callback: EncodersCallback): void; + availableFormats(callback: FormatsCallback): void; + getAvailableFormats(callback: FormatsCallback): void; // ffprobe - ffprobe(callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void - ffprobe(index: number, callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void - ffprobe(options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void - ffprobe(index: number, options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + /* tslint:disable:unified-signatures */ + ffprobe(callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void; + ffprobe(index: number, callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void; + ffprobe(options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void; + ffprobe(index: number, options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void; + /* tslint:enable:unified-signatures */ // recipes - saveToFile(output: string): FfmpegCommand - save(output: string): FfmpegCommand - writeToStream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable - pipe(stream: stream.Writable, options?: { end?: boolean }): stream.Writable - stream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable - takeScreenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand - thumbnail(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand - thumbnails(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand - screenshot(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand - screenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand - mergeToFile(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand - concatenate(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand - concat(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + saveToFile(output: string): FfmpegCommand; + save(output: string): FfmpegCommand; + writeToStream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable; + pipe(stream: stream.Writable, options?: { end?: boolean }): stream.Writable; + stream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable; + takeScreenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand; + thumbnail(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand; + thumbnails(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand; + screenshot(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand; + screenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand; + mergeToFile(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand; + concatenate(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand; + concat(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand; } - - function Ffmpeg(): FfmpegCommand - function Ffmpeg(options: FfmpegCommandOptions): FfmpegCommand - function Ffmpeg(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand - - export = Ffmpeg } +declare function Ffmpeg(options?: Ffmpeg.FfmpegCommandOptions): Ffmpeg.FfmpegCommand; +declare function Ffmpeg(input?: string | stream.Readable, options?: Ffmpeg.FfmpegCommandOptions): Ffmpeg.FfmpegCommand; + +export = Ffmpeg; diff --git a/types/fluent-ffmpeg/tslint.json b/types/fluent-ffmpeg/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fluent-ffmpeg/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/flux/flux-tests.ts b/types/flux/flux-tests.ts deleted file mode 100644 index 57c8fb3b20..0000000000 --- a/types/flux/flux-tests.ts +++ /dev/null @@ -1,126 +0,0 @@ -import flux = require('flux') -import FluxUtils = require('flux/utils') -import React = require('react') - -var Component = React.Component -var Container = FluxUtils.Container - -// -// Basic dispatcher usage -// - -var basicDispatcher = new flux.Dispatcher() - -// register(callback: (payload: any) => void): string -var id: string = basicDispatcher.register((payload) => { - // payload is type: any - payload.anything -}) - -// unregister(id: string): void -basicDispatcher.unregister(id) - -// waitFor(ids: string[]): void -basicDispatcher.waitFor([id]) - -// dispatch(payload: any): void -basicDispatcher.dispatch({ msg: 'hello' }) - -// isDispatching(): boolean -var dispatcherIsDispatching: boolean = basicDispatcher.isDispatching() - -// -// Typed payload -// - -enum ActionSource { Server, View } -enum ActionType { Create, Update, Delete } - -interface Action { - source: ActionSource - type: ActionType - data: Object -} - -var typedDispatcher = new flux.Dispatcher() - -var typedPayload: Action - -var typedStore = { - dispatcherID: typedDispatcher.register((payload) => { - typedPayload = payload - }) -} - -typedDispatcher.dispatch(typedPayload) - -// -// Derived dispatcher -// - -class CustomDispatcher extends flux.Dispatcher { - - // Dispatch an action with server as source - handleServerAction(type: ActionType, data: Object) { - this.dispatch({ - source: ActionSource.Server, - type: type, - data: data, - }) - } - - // Dispatch an action with view as source - handleViewAction(type: ActionType, data: Object) { - this.dispatch({ - source: ActionSource.View, - type: type, - data: data, - }) - } -} - -var customDispatcher = new CustomDispatcher() - -export = customDispatcher - - -// Sample Reduce Store -class CounterStore extends FluxUtils.ReduceStore { - getInitialState(): number { - return 0; - } - - reduce(state: number, action: any): number { - switch (action.type) { - case 'increment': - return state + 1; - - case 'square': - return state * state; - - default: - return state; - } - } -} - -const Store = new CounterStore(basicDispatcher); - -// Sample Flux container with CounterStore -class CounterContainer extends Component { - static getStores() { - return [Store]; - } - - static calculateState(prevState: any) { - return { - counter: Store.getState(), - }; - } - - render() { - return this.state.counter; - } -} - -const container = Container.create(CounterContainer); diff --git a/types/flux/index.d.ts b/types/flux/index.d.ts index 54fecd3a4e..7380613ce7 100644 --- a/types/flux/index.d.ts +++ b/types/flux/index.d.ts @@ -1,69 +1,12 @@ -// Type definitions for Flux 3.0 +// Type definitions for Flux 3.1 // Project: http://facebook.github.io/flux/ -// Definitions by: Steve Baker , Giedrius Grabauskas +// Definitions by: Steve Baker +// Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 -/// -/// +import * as Dispatcher from "./lib/Dispatcher"; -export = Flux; - -declare namespace Flux { - - /** - * Dispatcher class - * Create an instance to use throughout the application. - * Or extend it to create a derived dispatcher class. - * - * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, - * otherwise specify 'any' - * - * Examples: - * var dispatcher = new flux.Dispatcher() - * var typedDispatcher = new flux.Dispatcher() - * class DerivedDispatcher extends flux.Dispatcher { } - */ - export class Dispatcher { - - /** - * Create an instance of the Dispatcher class to use throughout the application. - * - * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, - * otherwise specify 'any' - * - * Examples: - * var dispatcher = new flux.Dispatcher() - * var typedDispatcher = new flux.Dispatcher() - */ - constructor(); - - /** - * Registers a callback that will be invoked with every payload sent to the dispatcher. - * Returns a string token to identify the callback to be used with waitFor() or unregister. - */ - register(callback: (payload: TPayload) => void): string; - - /** - * Unregisters a callback with the given ID token - */ - unregister(id: string): void; - - /** - * Waits for the callbacks with the specified IDs to be invoked before continuing execution - * of the current callback. This method should only be used by a callback in response - * to a dispatched payload. - */ - waitFor(IDs: string[]): void; - - /** - * Dispatches a payload to all registered callbacks - */ - dispatch(payload: TPayload): void; - - /** - * Gets whether the dispatcher is currently dispatching - */ - isDispatching(): boolean; - } -} +export { + Dispatcher +}; diff --git a/types/flux/lib/Dispatcher.d.ts b/types/flux/lib/Dispatcher.d.ts new file mode 100644 index 0000000000..045d633088 --- /dev/null +++ b/types/flux/lib/Dispatcher.d.ts @@ -0,0 +1,45 @@ +declare namespace Dispatcher { } + +declare class Dispatcher { + /** + * Create an instance of the Dispatcher class to use throughout the application. + * + * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, + * otherwise specify 'any' + * + * Examples: + * var dispatcher = new flux.Dispatcher() + * var typedDispatcher = new flux.Dispatcher() + */ + constructor(); + + /** + * Registers a callback that will be invoked with every payload sent to the dispatcher. + * Returns a string token to identify the callback to be used with waitFor() or unregister. + */ + register(callback: (payload: TPayload) => void): string; + + /** + * Unregisters a callback with the given ID token + */ + unregister(id: string): void; + + /** + * Waits for the callbacks with the specified IDs to be invoked before continuing execution + * of the current callback. This method should only be used by a callback in response + * to a dispatched payload. + */ + waitFor(IDs: string[]): void; + + /** + * Dispatches a payload to all registered callbacks + */ + dispatch(payload: TPayload): void; + + /** + * Gets whether the dispatcher is currently dispatching + */ + isDispatching(): boolean; +} + +export = Dispatcher; diff --git a/types/flux/lib/FluxContainer.d.ts b/types/flux/lib/FluxContainer.d.ts new file mode 100644 index 0000000000..54b578cc1d --- /dev/null +++ b/types/flux/lib/FluxContainer.d.ts @@ -0,0 +1,65 @@ +import * as Dispatcher from "./Dispatcher"; +import * as FluxStore from "./FluxStore"; +import * as React from "react"; + +/** + * A FluxContainer is used to subscribe a react component to multiple stores. + * The stores that are used must be returned from a static `getStores()` method. + * + * The component receives information from the stores via state. The state + * is generated using a static `calculateState()` method that each container must implement. + */ +/** + * Default options to create a Container. + * + * @interface RealOptions + */ +export interface RealOptions { + /** + * Default value: true + * + * @type {boolean} + */ + pure?: boolean; + /** + * Default value: false + * + * @type {boolean} + */ + withProps?: boolean; + /** + * Default value: false + * + * @type {boolean} + */ + withContext?: boolean; +} + +export type ComponentConstructor = React.ComponentClass | React.StatelessComponent; + +export interface ComponentStatic { + getStores(maybeProps?: TProps, maybeContext?: TContext): Array>; + calculateState(prevState: TState, maybeProps?: TProps, maybeContext?: TContext): TState; +} + +export type Component = ComponentConstructor & ComponentStatic; + +/** + * Create is used to transform a react class into a container + * that updates its state when relevant stores change. + * The provided base class must have static methods getStores() and calculateState(). + */ +export function create(base: Component, options?: RealOptions): Component; +export function create(base: Component, options?: RealOptions): Component; +export function create(base: Component, options?: RealOptions): Component; +export function create(base: Component & TStatic, options?: RealOptions): Component & TStatic; + +/** + * This is a way to connect stores to a functional stateless view. + */ +export function createFunctional( + viewFn: (props: TProps) => React.ReactElement, + getStores: (maybeProps?: TProps, maybeContext?: any) => Array>, + calculateState: (prevState?: TState, maybeProps?: TProps, maybeContext?: any) => TState, + options?: RealOptions +): Component; diff --git a/types/flux/lib/FluxMixinLegacy.d.ts b/types/flux/lib/FluxMixinLegacy.d.ts new file mode 100644 index 0000000000..2ce825e3da --- /dev/null +++ b/types/flux/lib/FluxMixinLegacy.d.ts @@ -0,0 +1,26 @@ +import * as FluxStore from "./FluxStore"; + +declare namespace FluxMixinLegacy { + interface Options { + withProps?: boolean; + } +} + +/** + * `FluxContainer` should be preferred over this mixin, but it requires using + * react with classes. So this mixin is provided where it is not yet possible + * to convert a container to be a class. + * + * This mixin should be used for React components that have state based purely + * on stores. `this.props` will not be available inside of `calculateState()`. + * + * This mixin will only `setState` not replace it, so you should always return + * every key in your state unless you know what you are doing. + * + * On the second calculateState when prevState is not null, the state will be + * updated to contain the previous foo AND the bar that was just returned. Only + * returning bar will not delete foo. + */ +declare function FluxMixinLegacy(stores: Array>, options?: FluxMixinLegacy.Options): any; + +export = FluxMixinLegacy; diff --git a/types/flux/lib/FluxReduceStore.d.ts b/types/flux/lib/FluxReduceStore.d.ts new file mode 100644 index 0000000000..71a7968812 --- /dev/null +++ b/types/flux/lib/FluxReduceStore.d.ts @@ -0,0 +1,36 @@ +import * as Store from "./FluxStore"; + +declare namespace FluxReduceStore { } + +/** + * This is the basic building block of a Flux application. All of your stores + * should extend this class. + */ +declare abstract class FluxReduceStore extends Store { + /** + * Getter that exposes the entire state of this store. + * If your state is not immutable you should override this and not expose state directly. + */ + getState(): TState; + + /** + * Constructs the initial state for this store. + * This is called once during construction of the store. + */ + abstract getInitialState(): TState; + + /** + * Reduces the current state, and an action to the new state of this store. + * All subclasses must implement this method. + * This method should be pure and have no side-effects. + */ + abstract reduce(state: TState, action: TPayload): TState; + + /** + * Checks if two versions of state are the same. + * You do not need to override this if your state is immutable. + */ + areEqual(one: TState, two: TState): boolean; +} + +export = FluxReduceStore; diff --git a/types/flux/lib/FluxStore.d.ts b/types/flux/lib/FluxStore.d.ts new file mode 100644 index 0000000000..a0b2384c72 --- /dev/null +++ b/types/flux/lib/FluxStore.d.ts @@ -0,0 +1,74 @@ +import * as Dispatcher from "./Dispatcher"; +import * as fbEmitter from "fbemitter"; + +declare namespace FluxStore { } + +/** + * This class represents the most basic functionality for a FluxStore. Do not + * extend this store directly; instead extend FluxReduceStore when creating a + * new store. + */ +declare abstract class FluxStore { + /** + * Constructs and registers an instance of this store with the given dispatcher. + */ + constructor(dispatcher: Dispatcher); + + /** + * Adds a listener to the store, when the store changes the given callback will be called. + * A token is returned that can be used to remove the listener. + * Calling the remove() function on the returned token will remove the listener. + */ + addListener(callback: () => void): fbEmitter.EventSubscription; + + /** + * Returns the dispatcher this store is registered with. + */ + getDispatcher(): Dispatcher; + + /** + * Returns the dispatch token that the dispatcher recognizes this store by. + * Can be used to waitFor() this store. + */ + getDispatchToken(): string; + + /** + * Ask if a store has changed during the current dispatch. + * Can only be invoked while dispatching. + * This can be used for constructing derived stores that depend on data from other stores. + */ + hasChanged(): boolean; + + /** + * Emit an event notifying all listeners that this store has changed. + * This can only be invoked when dispatching. + * Changes are de-duplicated and resolved at the end of this store's __onDispatch function. + */ + protected __emitChange(): void; + + /** + * This method encapsulates all logic for invoking __onDispatch. It should + * be used for things like catching changes and emitting them after the + * subclass has handled a payload. + */ + protected __invokeOnDispatch(payload: TPayload): void; + + /** + * Subclasses must override this method. + * This is how the store receives actions from the dispatcher. + * All state mutation logic must be done during this method. + */ + protected __onDispatch(payload: TPayload): void; + + protected __changed: boolean; + + protected __changeEvent: string; + + protected __className: string; + + protected __dispatcher: Dispatcher; + + protected __emitter: fbEmitter.EventEmitter; +} + +export = FluxStore; diff --git a/types/flux/test/Flux.ts b/types/flux/test/Flux.ts new file mode 100644 index 0000000000..6666b830aa --- /dev/null +++ b/types/flux/test/Flux.ts @@ -0,0 +1,71 @@ +import { Dispatcher } from "flux"; + +enum ActionSource { + Server, + View +} +enum ActionType { + Create, + Update, + Delete +} + +interface Action { + source: ActionSource; + type: ActionType; + data: {}; +} + +function dispatcherCallback(payload: Action) { + let source: ActionSource = payload.source; + let type: ActionType = payload.type; + let data: {} = payload.data; +} + +let dispatcherIsDispatching: boolean; +let dispatcherToken: string; + +const actionPayload = { + data: {}, + source: ActionSource.Server, + type: ActionType.Create +}; + +/** + * Basic dispatcher + */ +const basicDispatcher: Dispatcher = new Dispatcher(); +dispatcherToken = basicDispatcher.register(dispatcherCallback); +basicDispatcher.unregister(dispatcherToken); +basicDispatcher.waitFor([dispatcherToken]); +basicDispatcher.dispatch(actionPayload); +dispatcherIsDispatching = basicDispatcher.isDispatching(); + +/** + * Custom dispatcher + */ +class CustomDispatcher extends Dispatcher { + // Dispatch an action with server as source + handleServerAction(type: ActionType, data: {}) { + this.dispatch({ + source: ActionSource.Server, + type, + data + }); + } + // Dispatch an action with view as source + handleViewAction(type: ActionType, data: {}) { + this.dispatch({ + source: ActionSource.View, + type, + data + }); + } +} + +const customDispatcher: CustomDispatcher = new CustomDispatcher(); +dispatcherToken = customDispatcher.register(dispatcherCallback); +customDispatcher.unregister(dispatcherToken); +customDispatcher.dispatch(actionPayload); +customDispatcher.waitFor([dispatcherToken]); +dispatcherIsDispatching = customDispatcher.isDispatching(); diff --git a/types/flux/test/FluxUtils.tsx b/types/flux/test/FluxUtils.tsx new file mode 100644 index 0000000000..1cd3705fab --- /dev/null +++ b/types/flux/test/FluxUtils.tsx @@ -0,0 +1,80 @@ +import { Dispatcher } from "flux"; +import { ReduceStore, Container } from "flux/utils"; +import * as React from "react"; + +interface Payload { + type: string; +} + +const basicDispatcher = new Dispatcher(); + +// Sample Reduce Store +class CounterStore extends ReduceStore { + getInitialState(): number { + return 0; + } + + reduce(state: number, action: Payload): number { + switch (action.type) { + case 'increment': + return state + 1; + case 'square': + return state * state; + default: + return state; + } + } +} +const Store = new CounterStore(basicDispatcher); + +// Sample Flux container with Store +interface Props { + a: string; + b: boolean; +} + +interface State { + counter: number; +} + +class CounterContainer extends React.Component { + static getStores() { + return [Store]; + } + + static a: string = "asd"; + + static calculateState(prevState: State, props: Props): State { + return { + counter: Store.getState() - (props.b ? 0 : 1) + }; + } + + render() { + return

+ {this.state.counter} +
; + } +} + +const ContainerComponent1 = Container.create(CounterContainer, { withProps: true }); +; + +const ContainerComponent2 = Container.create(CounterContainer, { withProps: true }); +; + +const ContainerComponent3 = Container.create(CounterContainer, { withProps: true }); +; + +// Functional flux container with Store +const FunctionalContainerComponent = Container.createFunctional( + (props) => { + return
+ {props.a} {props.b} +
; + }, + () => [Store], + (prevState) => ({ counter: Store.getState() }) +); + +; diff --git a/types/flux/tsconfig.json b/types/flux/tsconfig.json index 45255c7d7a..540faa9d2b 100644 --- a/types/flux/tsconfig.json +++ b/types/flux/tsconfig.json @@ -5,20 +5,27 @@ "es6", "dom" ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ "../" ], + "jsx": "react", "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "forceConsistentCasingInFileNames": true, + "noEmit": true }, "files": [ "index.d.ts", - "utils/index.d.ts", - "flux-tests.ts" + "utils.d.ts", + "lib/Dispatcher.d.ts", + "lib/FluxContainer.d.ts", + "lib/FluxMixinLegacy.d.ts", + "lib/FluxReduceStore.d.ts", + "lib/FluxStore.d.ts", + "test/Flux.ts", + "test/FluxUtils.tsx" ] } \ No newline at end of file diff --git a/types/flux/tslint.json b/types/flux/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/flux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/flux/utils.d.ts b/types/flux/utils.d.ts new file mode 100644 index 0000000000..4eb3d96e99 --- /dev/null +++ b/types/flux/utils.d.ts @@ -0,0 +1,11 @@ +import * as Container from "./lib/FluxContainer"; +import * as Mixin from "./lib/FluxMixinLegacy"; +import * as ReduceStore from "./lib/FluxReduceStore"; +import * as Store from "./lib/FluxStore"; + +export { + Container, + Mixin, + ReduceStore, + Store +}; diff --git a/types/flux/utils/index.d.ts b/types/flux/utils/index.d.ts deleted file mode 100644 index b223945181..0000000000 --- a/types/flux/utils/index.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -// Type definitions for Flux Utils 3.0 -// Project: http://facebook.github.io/flux/ -// Definitions by: Steve Baker , Giedrius Grabauskas -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - -import * as React from 'react'; -import * as Flux from 'flux'; -import * as fbEmitter from 'fbemitter'; - -export = FluxUtils; - -declare namespace FluxUtils { - /** - * Default options to create a Container with - * - * @interface RealOptions - */ - interface RealOptions { - /** - * Default value: true - * - * @type {boolean} - */ - pure?: boolean; - /** - * Default value: false - * - * @type {boolean} - */ - withProps?: boolean; - /** - * Default value: false - * - * @type {boolean} - */ - withContext?: boolean; - } - - export class Container { - constructor(); - /** - * Create is used to transform a react class into a container - * that updates its state when relevant stores change. - * The provided base class must have static methods getStores() and calculateState(). - */ - static create(base: React.ComponentClass, options?: RealOptions): React.ComponentClass; - - - - /** - * This is a way to connect stores to a functional stateless view - */ - static createFunctional( - viewFn: (props: State) => React.ReactElement, - getStores: (props?: Props, context?: any) => FluxUtils.Store[], - calculateState: (prevState?: State, props?: Props, context?: any) => State, - options?: RealOptions - ): React.ComponentClass; - } - - export class ReduceStore extends Store { - /** - * Getter that exposes the entire state of this store. - * If your state is not immutable you should override this and not expose state directly. - */ - getState(): T; - - /** - * Constructs the initial state for this store. - * This is called once during construction of the store. - */ - getInitialState(): T; - - /** - * Reduces the current state, and an action to the new state of this store. - * All subclasses must implement this method. - * This method should be pure and have no side-effects. - */ - reduce(state: T, action: TPayload): T; - - /** - * Checks if two versions of state are the same. - * You do not need to override this if your state is immutable. - */ - areEqual(one: T, two: T): boolean; - - } - - export class Store { - - /** - * Constructs and registers an instance of this store with the given dispatcher. - */ - constructor(dispatcher: Flux.Dispatcher); - - /** - * Adds a listener to the store, when the store changes the given callback will be called. - * A token is returned that can be used to remove the listener. - * Calling the remove() function on the returned token will remove the listener. - */ - addListener(callback: Function): fbEmitter.EventSubscription; - - /** - * Returns the dispatcher this store is registered with. - */ - getDispatcher(): Flux.Dispatcher; - - /** - * Returns the dispatch token that the dispatcher recognizes this store by. - * Can be used to waitFor() this store. - */ - getDispatchToken(): string; - - /** - * Ask if a store has changed during the current dispatch. - * Can only be invoked while dispatching. - * This can be used for constructing derived stores that depend on data from other stores. - */ - hasChanged(): boolean; - - /** - *Emit an event notifying all listeners that this store has changed. - * This can only be invoked when dispatching. - * Changes are de-duplicated and resolved at the end of this store's __onDispatch function. - */ - __emitChange(): void; - - /** - * Subclasses must override this method. - * This is how the store receives actions from the dispatcher. - * All state mutation logic must be done during this method. - */ - __onDispatch(payload: TPayload): void; - } -} - diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index a4d34126ea..b4c9a648ac 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for fs-extra-promise +// Type definitions for fs-extra-promise 1.0 // Project: https://github.com/overlookmotel/fs-extra-promise // Definitions by: midknight41 , Jason Swearingen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// @@ -10,10 +11,15 @@ import * as stream from 'stream'; import { Stats } from 'fs'; import * as Promise from 'bluebird'; -import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MkdirOptions, MoveOptions } from 'fs-extra'; +import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MoveOptions } from 'fs-extra'; export * from 'fs-extra'; +export interface MkdirOptions { + fs?: any; + mode?: number; +} + //promisified versions export declare function copyAsync(src: string, dest: string): Promise; export declare function copyAsync(src: string, dest: string, filter: CopyFilter): Promise; diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index d39cae8d6f..005857e48c 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,106 +1,214 @@ import * as fs from 'fs-extra'; import * as Path from 'path'; +const len = 2; const src = ""; const dest = ""; const file = ""; const dir = ""; const path = ""; const data = ""; +const uid = 0; +const gid = 0; +const fd = 0; +const modeNum = 0; +const modeStr = ""; const object = {}; -const errorCallback = (err: Error) => {}; +const errorCallback = (err: Error) => { }; const readOptions: fs.ReadOptions = { - reviver : {} + reviver: {} }; const writeOptions: fs.WriteOptions = { - replacer: {} + replacer: {} }; +fs.moveSync(src, dest, {}); +fs.move(src, dest, {}).then(() => { + // stub +}); +fs.move(src, dest).then(() => { + // stub +}); +fs.move(src, dest, {}, () => { + // stub +}); +fs.move(src, dest, () => { + // stub +}); + +fs.copy(src, dest).then(() => { + // stub +}); +fs.copy(src, dest, { overwrite: true }).then(() => { + // stub +}); fs.copy(src, dest, errorCallback); -fs.copy(src, dest, (src: string) => { - return false; -}, errorCallback); +fs.copy(src, dest, (src: string) => false, errorCallback); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false }, errorCallback ); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ }, errorCallback ); fs.copySync(src, dest); -fs.copySync(src, dest, (src: string) => { - return false; -}); +fs.copySync(src, dest, (src: string) => false); fs.copySync(src, dest, /.*/); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false } ); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ } ); +fs.createFile(file).then(() => { + // stub +}); fs.createFile(file, errorCallback); fs.createFileSync(file); +fs.mkdirs(dir).then(() => { + // stub +}); +fs.mkdirp(dir).then(() => { + // stub +}); fs.mkdirs(dir, errorCallback); -fs.mkdirs(dir, {}, errorCallback); fs.mkdirsSync(dir); -fs.mkdirsSync(dir, {}); fs.mkdirp(dir, errorCallback); -fs.mkdirp(dir, {}, errorCallback); fs.mkdirpSync(dir); -fs.mkdirpSync(dir, {}); +fs.outputFile(file, data).then(() => { + // stub +}); fs.outputFile(file, data, errorCallback); fs.outputFileSync(file, data); -fs.outputJson(file, data, errorCallback); + +fs.outputJson(file, data, { + spaces: 2 +}).then(() => { + // stub +}); +fs.outputJson(file, data, { + spaces: 2 +}, errorCallback); fs.outputJSON(file, data, errorCallback); +fs.outputJSON(file, data).then(() => { + // stub +}); fs.outputJsonSync(file, data); fs.outputJSONSync(file, data); -fs.readJson(file, (error: Error, jsonObject: any) => {}); -fs.readJson(file, readOptions, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => {}); +fs.readJson(file).then(() => { + // stub +}); + +fs.readJson(file, readOptions).then(() => { + // stub +}); +fs.readJson(file, (error: Error, jsonObject: any) => { }); +fs.readJson(file, readOptions, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => { }); fs.readJsonSync(file, readOptions); fs.readJSONSync(file, readOptions); fs.remove(dir, errorCallback); +fs.remove(dir).then(() => { + // stub +}); fs.removeSync(dir); +fs.writeJson(file, object).then(() => { + // stub +}); +fs.writeJSON(file, object).then(() => { + // stub +}); fs.writeJson(file, object, errorCallback); fs.writeJson(file, object, writeOptions, errorCallback); fs.writeJSON(file, object, errorCallback); fs.writeJSON(file, object, writeOptions, errorCallback); - +fs.writeJson(file, object, writeOptions).then(() => { + // stub +}); +fs.writeJSON(file, object, writeOptions).then(() => { + // stub +}); fs.writeJsonSync(file, object, writeOptions); fs.writeJSONSync(file, object, writeOptions); +fs.ensureDir(path).then(() => { + // stub +}); fs.ensureDir(path, errorCallback); fs.ensureDirSync(path); + +fs.ensureFile(path).then(() => { + // stub +}); fs.ensureFile(path, errorCallback); fs.ensureFileSync(path); +fs.ensureLink(path).then(() => { + // stub +}); fs.ensureLink(path, errorCallback); fs.ensureLinkSync(path); +fs.ensureSymlink(path).then(() => { + // stub +}); fs.ensureSymlink(path, errorCallback); fs.ensureSymlinkSync(path); +fs.emptyDir(path).then(() => { + // stub +}); fs.emptyDir(path, errorCallback); fs.emptyDirSync(path); +fs.pathExists(path).then((_exist: boolean) => { + // stub +}); +fs.pathExists(path, (_err: Error, _exists: boolean) => { }); +const x: boolean = fs.pathExistsSync(path); + +fs.rename(src, dest, errorCallback); +fs.renameSync(src, dest); +fs.truncate(path, len, errorCallback); +fs.truncateSync(path, len); +fs.chown(path, uid, gid, errorCallback); +fs.chownSync(path, uid, gid); +fs.fchown(fd, uid, gid, errorCallback); +fs.fchownSync(fd, uid, gid); +fs.lchown(path, uid, gid, errorCallback); +fs.lchownSync(path, uid, gid); +fs.chmod(path, modeNum, errorCallback); +fs.chmod(path, modeStr, errorCallback); +fs.chmodSync(path, modeNum); +fs.chmodSync(path, modeStr); +fs.fchmod(fd, modeNum, errorCallback); +fs.fchmod(fd, modeStr, errorCallback); +fs.fchmodSync(fd, modeNum); +fs.fchmodSync(fd, modeStr); +fs.lchmod(path, modeStr, errorCallback); +fs.lchmod(path, modeNum, errorCallback); +fs.lchmodSync(path, modeNum); +fs.lchmodSync(path, modeStr); +fs.statSync(path); +fs.lstatSync(path); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index c46dddba85..481fbad644 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,9 +1,11 @@ -// Type definitions for fs-extra 2.1 +// Type definitions for fs-extra 3.0 // Project: https://github.com/jprichardson/node-fs-extra -// Definitions by: midknight41 , Brendan Forster +// Definitions by: Alan Agius +// midknight41 +// Brendan Forster +// Mees van Dijk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts +// TypeScript Version: 2.2 /// @@ -11,123 +13,255 @@ import { Stats } from "fs"; export * from "fs"; -export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, filter: CopyFilter, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, options: CopyOptions, callback?: (err: Error) => void): void; +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copySync(src: string, dest: string, options?: CopyOptions): void; -export declare function copySync(src: string, dest: string): void; -export declare function copySync(src: string, dest: string, filter: CopyFilter): void; -export declare function copySync(src: string, dest: string, options: CopyOptions): void; +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function moveSync(src: string, dest: string, options?: MoveOptions): void; -export declare function move(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function move(src: string, dest: string, options: MoveOptions, callback?: (err: Error) => void): void; +export function createFile(file: string): Promise; +export function createFile(file: string, callback: (err: Error) => void): void; +export function createFileSync(file: string): void; -export declare function createFile(file: string, callback?: (err: Error) => void): void; -export declare function createFileSync(file: string): void; +export function ensureDir(path: string): Promise; +export function ensureDir(path: string, callback: (err: Error) => void): void; +export function ensureDirSync(path: string): void; -export declare function mkdirs(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirs(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirsSync(dir: string, options?: MkdirOptions): void; -export declare function mkdirpSync(dir: string, options?: MkdirOptions): void; +export function mkdirs(dir: string): Promise; +export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirp(dir: string): Promise; +export function mkdirp(dir: string, callback: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; -export declare function outputFile(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputFileSync(file: string, data: any): void; +export function outputFile(file: string, data: any): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFileSync(file: string, data: any): void; -export declare function outputJson(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJsonSync(file: string, data: any): void; -export declare function outputJSONSync(file: string, data: any): void; +export function readJson(file: string, options?: ReadOptions): Promise; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options?: ReadOptions): Promise; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJsonSync(file: string, options?: ReadOptions): any; +export function readJSONSync(file: string, options?: ReadOptions): any; -export declare function readJsonSync(file: string, options?: ReadOptions): any; -export declare function readJSONSync(file: string, options?: ReadOptions): any; +export function remove(dir: string): Promise; +export function remove(dir: string, callback: (err: Error) => void): void; +export function removeSync(dir: string): void; -export declare function remove(dir: string, callback?: (err: Error) => void): void; -export declare function removeSync(dir: string): void; +export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options?: WriteOptions): Promise; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; +export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; -export declare function writeJson(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJson(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options?: WriteOptions): Promise; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; -export declare function writeJsonSync(file: string, object: any, options?: WriteOptions): void; -export declare function writeJSONSync(file: string, object: any, options?: WriteOptions): void; +export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; +export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; -export declare function ensureDir(path: string, callback: (err: Error) => void): void; -export declare function ensureDirSync(path: string): void; +export function ensureFile(path: string): Promise; +export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFileSync(path: string): void; -export declare function ensureFile(path: string, callback: (err: Error) => void): void; -export declare function ensureFileSync(path: string): void; +export function ensureLink(path: string): Promise; +export function ensureLink(path: string, callback: (err: Error) => void): void; +export function ensureLinkSync(path: string): void; -export declare function ensureLink(path: string, callback: (err: Error) => void): void; -export declare function ensureLinkSync(path: string): void; +export function ensureSymlink(path: string): Promise; +export function ensureSymlink(path: string, callback: (err: Error) => void): void; +export function ensureSymlinkSync(path: string): void; -export declare function ensureSymlink(path: string, callback: (err: Error) => void): void; -export declare function ensureSymlinkSync(path: string): void; +export function emptyDir(path: string): Promise; +export function emptyDir(path: string, callback: (err: Error) => void): void; +export function emptyDirSync(path: string): void; -export declare function emptyDir(path: string, callback?: (err: Error) => void): void; -export declare function emptyDirSync(path: string): boolean; +export function pathExists(path: string): Promise; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExistsSync(path: string): boolean; -export interface WalkEventEmitter extends NodeJS.ReadableStream { - on(event: 'data', callback: (file: WalkEventFile) => void): this; - on(event: 'readable', callback: (this: PathEntryStream) => void): this; - on(event: 'error', callback: (error: Error, item: PathEntry) => void): this; - on(event: 'end', callback: () => void): this; - on(event: string | symbol, callback: Function): this; -} +// fs async methods +// copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts -export interface WalkEventFile { +/** Tests a user's permissions for the file specified by path. */ +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode?: number): Promise; + +export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; + +export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function chmod(path: string | Buffer, mode: string | number): Promise; + +export function chown(path: string | Buffer, uid: number, gid: number): Promise; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; + +export function close(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function close(fd: number): Promise; + +export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: string | number): Promise; + +export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number): Promise; + +export function fdatasync(fd: number, callback: () => void): void; +export function fdatasync(fd: number): Promise; + +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number): Promise; + +export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number): Promise; + +export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len?: number): Promise; + +export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number): Promise; +export function futimes(fd: number, atime: Date, mtime: Date): Promise; + +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number): Promise; + +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; + +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: string | Buffer): Promise; + +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer): Promise; + +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; + +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; + +export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; +export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; +// tslint:disable-next-line:unified-signatures +export function readFile(file: string | Buffer | number, encoding: string): Promise; +export function readFile(file: string | Buffer | number): Promise; + +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir(path: string | Buffer): Promise; + +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: string | Buffer): Promise; + +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; + +export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: string, newPath: string): Promise; + +/** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rmdir(path: string | Buffer): Promise; + +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: string | Buffer): Promise; + +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; + +export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len?: number): Promise; + +/** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function unlink(path: string | Buffer): Promise; + +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; +export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; + +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; + +export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; + +/** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ +export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; +export function mkdtemp(prefix: string): Promise; + +export interface PathEntry { path: string; stats: Stats; } -export interface WalkOptions { - /** - * Control how results are enumerated from `readdir`: - * - 'shift' will return the first element from the array. - * - 'pop' will return the last element from the array. - * - * If not specified, the default behaviour is 'shift' - */ - queueMethod?: 'pop' | 'shift'; - /** - * Provide a function to sort the paths before they are enumerated - */ - pathSorter?: (left: string, right: string) => number; - /** - * An optional object to override the default `fs` APIs for testing purposes - */ - fs?: Object; - /** - * Provide a function to exclude certain file paths. The function should - * return true when the element should be kept, and false otherwise. - */ - filter?: (path: string, index: number, array: Array) => boolean; +export interface PathEntryStream { + read(): PathEntry | null; } -export type PathEntry = { - path: string; - stats: Stats; -} - -export type PathEntryStream = { - read(): PathEntry | null -} - -export interface CopyFilterFunction { - (src: string): boolean -} +export type CopyFilterFunction = (src: string) => boolean; export type CopyFilter = CopyFilterFunction | RegExp; export interface CopyOptions { - clobber?: boolean; dereference?: boolean; overwrite?: boolean; preserveTimestamps?: boolean; @@ -137,28 +271,23 @@ export interface CopyOptions { } export interface MoveOptions { - clobber? : boolean; + overwrite?: boolean; limit?: number; } export interface ReadOptions { throws?: boolean; - fs?: Object; + fs?: object; reviver?: any; encoding?: string; flag?: string; } export interface WriteOptions { - fs?: Object; + fs?: object; replacer?: any; spaces?: number; encoding?: string; flag?: string; mode?: number; } - -export interface MkdirOptions { - fs?: any; - mode?: number; -} diff --git a/types/fs-extra/tsconfig.json b/types/fs-extra/tsconfig.json index 6337361eed..818b38896c 100644 --- a/types/fs-extra/tsconfig.json +++ b/types/fs-extra/tsconfig.json @@ -1,22 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "fs-extra-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-tests.ts" + ] +} diff --git a/types/fs-extra/tslint.json b/types/fs-extra/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fullcalendar/fullcalendar-tests.ts b/types/fullcalendar/fullcalendar-tests.ts index 4557a94eef..ca456013af 100644 --- a/types/fullcalendar/fullcalendar-tests.ts +++ b/types/fullcalendar/fullcalendar-tests.ts @@ -417,13 +417,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick(date, allDay, jsEvent, view) { - if (allDay) { - alert('Clicked on the entire day: ' + date); - } else { - alert('Clicked on the slot: ' + date); - } - + dayClick(date, jsEvent, view) { alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); alert('Current view: ' + view.name); diff --git a/types/fullcalendar/index.d.ts b/types/fullcalendar/index.d.ts index e040d613f9..2fedd216c6 100644 --- a/types/fullcalendar/index.d.ts +++ b/types/fullcalendar/index.d.ts @@ -90,7 +90,7 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr // Clicking & Hovering - http://fullcalendar.io/docs/mouse/ - dayClick?(date: Date, allDay: boolean, jsEvent: MouseEvent, view: ViewObject): void; + dayClick?(date: Date, jsEvent: MouseEvent, view: ViewObject): void; eventClick?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): any; // return type boolean or void eventMouseover?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): void; eventMouseout?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): void; diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 1d389d59e9..0766f3b914 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -41,6 +41,14 @@ function test_getAuthResponse() { var authResponseWithAuth = user.getAuthResponse(true); } +function test_reloadAuthResponse() { + gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse() + .then(response => { + let token = response.access_token; + let expires_in = response.expires_in + }) +} + function test_render() { var success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); @@ -103,10 +111,10 @@ function handleClientLoad() { } function initClient() { gapi.client.init({ - apiKey: apiKey, - discoveryDocs: discoveryDocs, - clientId: clientId, - scope: scopes + apiKey: apiKey, + discoveryDocs: discoveryDocs, + clientId: clientId, + scope: scopes }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); @@ -136,10 +144,10 @@ function handleSignoutClick(event: MouseEvent) { function makeApiCall() { gapi.client.people.people.get({ resourceName: 'people/me' - }).then(function(resp) { + }).then(function (resp) { var p = document.createElement('p'); var name = resp.result.names[0].givenName; - p.appendChild(document.createTextNode('Hello, '+name+'!')); + p.appendChild(document.createTextNode('Hello, ' + name + '!')); document.getElementById('content').appendChild(p); }); } diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index 402da68699..de75d26ca2 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -131,9 +131,9 @@ declare namespace gapi.auth2 { id_token: string; login_hint: string; scope: string; - expires_in: string; - first_issued_at: string; - expires_at: string; + expires_in: number; + first_issued_at: number; + expires_at: number; } /** @@ -170,6 +170,11 @@ declare namespace gapi.auth2 { */ getAuthResponse(includeAuthorizationData?: boolean): AuthResponse; + /** + * Forces a refresh of the access token, and then returns a Promise for the new AuthResponse. + */ + reloadAuthResponse(): Promise; + /** * Returns true if the user granted the specified scopes. */ diff --git a/types/gapi.people/index.d.ts b/types/gapi.people/index.d.ts index 86bf930beb..894dd8a0d1 100644 --- a/types/gapi.people/index.d.ts +++ b/types/gapi.people/index.d.ts @@ -117,11 +117,15 @@ declare namespace gapi.client.people { value: string; type: NicknameType; } - + interface CoverPhoto { + metadata: FieldMetadata; + url: string; } interface Photo { + metadata: FieldMetadata; + url: string; } interface Gender { diff --git a/types/gapi/index.d.ts b/types/gapi/index.d.ts index 8f8e621fa3..9af6258966 100644 --- a/types/gapi/index.d.ts +++ b/types/gapi/index.d.ts @@ -148,7 +148,9 @@ declare namespace gapi.client { /** * The scopes to request, as a space-delimited string. */ - scope?: string + scope?: string, + + hosted_domain?: string; }): Promise; interface RequestOptions { diff --git a/types/google-cloud__storage/google-cloud__storage-tests.ts b/types/google-cloud__storage/google-cloud__storage-tests.ts new file mode 100644 index 0000000000..e701fe5681 --- /dev/null +++ b/types/google-cloud__storage/google-cloud__storage-tests.ts @@ -0,0 +1,398 @@ +// import file system i/o api +import * as fs from "fs"; + +// import Google Cloud Storage +import { + Acl, + Bucket, + Channel, + File, + ApiResponse, + BucketConfig, + BucketFileOptions, + BucketGetOptions, + BucketMetadata, + BucketPrivacyOptions, + BucketQuery, + ChannelConfig, + DownloadOptions, + FileMetadata, + FilePrivateOptions, + ReadStreamOptions, + SignedPolicy, + SignedPolicyOptions, + SignedUrlConfig, + WriteStreamOptions, + UploadOptions, + Storage +} from "@google-cloud/storage"; + +/** + * Test the storage service. + * @class TestStorage + */ +export class TestStorage { + // constants + static BUCKET_CONFIG: BucketConfig = { + multiRegional: true + }; + + // import Storage class + static gcs: Storage; + + // the bucket + private buckets: Bucket[] = []; + + /** + * @constructor + */ + constructor() { + // nothing to do + } + + /** + * Returns the bucket. + * @method bucket + * @param {string} name + * @return {Bucket} + */ + bucket(name: string): Bucket { + return TestStorage.gcs.bucket(name); + } + + /** + * Create a new bucket. + * @param {string} name + * @param {BucketConfig} metadata + * @return {Promise<[Bucket, ApiResponse]>} + */ + createBucket(name: string, config?: BucketConfig): Promise<[Bucket, ApiResponse]> { + // overwrite default values with custom config + config = Object.assign(TestStorage.BUCKET_CONFIG, config); + + return TestStorage.gcs.createBucket(name, config); + } + + /** + * Query for buckets. + * @param {BucketQuery} query + */ + getBuckets(query?: BucketQuery): Promise<[Bucket[]]> { + return TestStorage.gcs.getBuckets(query); + } +} + +/** + * The bucket API wrapper. + * @class TestBucket + */ +export class TestBucket { + // the bucket in the cloud + bucket: Bucket; + + /** + * Create a bucket. + * @param {BucketConfig} config + * @return {Promise<[Bucket, ApiResponse]>} + */ + create(config?: BucketConfig): Promise<[Bucket, ApiResponse]> { + return this.bucket.create(config); + } + + /** + * Create a channel that will be notified when objects in this bucket changes. + * @method createChannel + * @param {string} id + * @param {ChannelConfig} config + * @return {Promise<[Channel, ApiResponse]>} + */ + createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]> { + return this.bucket.createChannel(id, config); + } + + /** + * Delete the bucket. + * @method delete + * @return {Promise<[ApiResponse]>} + */ + delete(): Promise<[ApiResponse]> { + return this.bucket.delete(); + } + + /** + * Iterate over the bucket's files, calling file.delete() on each. + * @method deleteFiles + * @return {Promise} + */ + deleteFiles(query?: BucketQuery): Promise { + return this.bucket.deleteFiles(query); + } + + /** + * Check if the bucket exists. + * @method exists + * @return {Promise<[boolean]>} + */ + exists(): Promise<[boolean]> { + return this.bucket.exists(); + } + + /** + * Create a File object. + * @method file + * @param {string} name + * @param {BucketFileOptions} options + */ + file(name: string, options?: BucketFileOptions): File { + return this.bucket.file(name); + } + + /** + * Get a bucket if it exists. + * @method get + * @param {BucketGetOptions} options + */ + get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]> { + return this.bucket.get(options); + } + + /** + * Get File objects for the files currently in the bucket + * @method getFiles + * @param {BucketQuery} query + * @return {Promise<[File[]]>} + */ + getFiles(query?: BucketQuery): Promise<[File[]]> { + return this.bucket.getFiles(query); + } + + /** + * Get File objects for the files currently in the bucket as a readable object stream. + * @method getFilesStream + * @param {BucketQuery} query + * @return {ReadStream} + */ + getFilesStream(query?: BucketQuery): fs.ReadStream { + return this.bucket.getFilesStream(query); + } + + /** + * Get the bucket's metadata. + * @method getMetadata + * @return {Promise<[BucketMetadata, ApiResponse]>} + */ + getMetadata(): Promise<[BucketMetadata, ApiResponse]> { + return this.bucket.getMetadata(); + } + + /** + * Make the bucket listing private. + * @method makePrivate + * @param {} options + * @return Promise<[File[]]> + */ + makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]> { + return this.bucket.makePrivate(options); + } + + /** + * Make the bucket publicly readable. + * @method makePublic + * @param {} options + * @return Promise<[File[]]> + */ + makePublic(options?: BucketPrivacyOptions): Promise<[File[]]> { + return this.bucket.makePublic(options); + } + + /** + * Set the bucket's metadata. + * @method setMetadata + * @param {BucketMetadata} metadata + * @return {Promise<[ApiResponse]>} + */ + setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]> { + return this.bucket.setMetadata(metadata); + } + + /** + * Upload a file. + * @method upload + * @param {localPath} string + * @param {UploadOptions} options + */ + upload(localPath: string, options?: UploadOptions): Promise<[File]> { + return this.bucket.upload(localPath, options); + } +} + +/** + * The file API wrapper. + * @class TestFile + */ +export class TestFile { + // the file in the cloud + file: File; + + /** + * Copy this file to another file. + * By default, this will copy the file to the same bucket, but you can choose to copy it to another + * Bucket by providing a Bucket or File object or a URL starting with "gs:// ". + * @method copy + * @param {string} destination + * @return Promise<[File, ApiResponse]> + */ + + copy(destination: string | Bucket | File): Promise<[File, ApiResponse]> { + return this.file.copy(destination); + } + + /** + * Create a readable stream to read the contents of the remote file. + * It can be piped to a writable stream or listened to for 'data' events to read a file's contents. + * @method createReadStream + * @param {ReadStreamOptions} options + * @return {ReadStream} + */ + createReadStream(options?: ReadStreamOptions): fs.ReadStream { + return this.file.createReadStream(options); + } + + /** + * Create a writable stream to overwrite the contents of the file in your bucket. + * @method createWriteStream + * @param {WriteStreamOptions} options + * @return {WriteStream} + */ + createWriteStream(options?: WriteStreamOptions): fs.WriteStream { + return this.file.createWriteStream(options); + } + + /** + * Delete the file. + * @method delete + * @return {Promise<[ApiResponse]>} + */ + delete(): Promise<[ApiResponse]> { + return this.file.delete(); + } + + /** + * Convenience method to download a file into memory or to a local destination. + * @method download + * @param {DownloadOptions} options + * @return {Promise<[string]>} + */ + download(options?: DownloadOptions): Promise<[string]> { + return this.file.download(options); + } + + /** + * Check if the file exists. + * @method exists + * @return {Promise<[boolean]>} + */ + exists(): Promise<[boolean]> { + return this.file.exists(); + } + + /** + * Get a file object and its metadata if it exists. + * @method get + * @return {Promise<[File, ApiResponse]>} + */ + get(): Promise<[File, ApiResponse]> { + return this.file.get(); + } + + /** + * Get the file's metadata. + * @method getMetadata + * @return {Promise<[FileMetadata, ApiResponse]>} + */ + getMetadata(): Promise<[FileMetadata, ApiResponse]> { + return this.file.getMetadata(); + } + + /** + * Get a signed policy document to allow a user to upload data with a POST request + * @method getSignedPolicy + * @param {SignedPolicyOptions} options + * @return {Promise<[SignedPolicy]>} + */ + getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]> { + return this.file.getSignedPolicy(options); + } + + /** + * Get a signed URL to allow limited time access to the file + * @method getSignedUrl + * @param {SignedUrlConfig} config + * @return {Promise<[string]>} + */ + getSignedUrl(config?: SignedUrlConfig): Promise<[string]> { + return this.file.getSignedUrl(config); + } + + /** + * Make a file private to the project and remove all other permissions. + * @method makePrivate + * @param {FilePrivateOptions} options + * @return {Promise<[ApiResponse]>} + */ + makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]> { + return this.file.makePrivate(options); + } + + /** + * Set a file to be publicly readable and maintain all previous permissions. + * @method makePublic + * @return {Promise<[ApiResponse]>} + */ + makePublic(): Promise<[ApiResponse]> { + return this.file.makePublic(); + } + + /** + * Move this file to another location. + * By default, this will move the file to the same bucket, but you can choose to move it to + * another Bucket by providing a Bucket or File object or a URL beginning with "gs:// ". + * @method move + * @param {string|Bucket|File} destination + * @return {Promise<[File, ApiResponse]>} + */ + move(destination: string | Bucket | File): Promise<[File, ApiResponse]> { + return this.file.move(destination); + } + + /** + * Write arbitrary data to a file. + * @param {string} data + * @param {WriteStreamOptions} options + * @return {Promise} + */ + save(data: string, options?: WriteStreamOptions): Promise { + return this.file.save(data); + } + + /** + * The Storage API allows you to use a custom key for server-side encryption. + * @param {string|Buffer} encryptionKey + * @return {File} + */ + setEncryptionKey(encryptionKey: string | Buffer): File { + return this.file.setEncryptionKey(encryptionKey); + } + + /** + * Merge the given metadata with the current remote file's metadata. + * This will set metadata if it was previously unset or update previously set metadata. + * To unset previously set metadata, set its value to null. + * @method setMetadata + * @param {FileMetadata} metadata + * @return {Promise<[ApiResponse]>} + */ + setMetadata(metadata: FileMetadata): Promise<[ApiResponse]> { + return this.file.setMetadata(metadata); + } +} diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts new file mode 100644 index 0000000000..e97249be24 --- /dev/null +++ b/types/google-cloud__storage/index.d.ts @@ -0,0 +1,353 @@ +// Type definitions for @google-cloud/storage 0.6 +// Project: https://github.com/GoogleCloudPlatform/google-cloud-node/tree/master/packages/storage +// Definitions by: Brian Love +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "@google-cloud/storage" { + export * from "@google-cloud/storage/bucket"; + export * from "@google-cloud/storage/channel"; + export * from "@google-cloud/storage/file"; + export * from "@google-cloud/storage/storage"; +} + +declare module "@google-cloud/storage/bucket" { + import { ReadStream } from "fs"; + import { Channel, ChannelConfig } from "@google-cloud/storage/channel"; + import { File } from "@google-cloud/storage/file"; + import { + Acl, + ApiResponse, + UploadOptions + } from "@google-cloud/storage/storage"; + + /** + * A bucket in the cloud. + */ + class Bucket { + acl: Acl; + combine(sources: string[] | File[], destination: string [] | File[]): Promise<[File, ApiResponse]>; + create(config?: BucketConfig): Promise<[Bucket, ApiResponse]>; + createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]>; + delete(): Promise<[ApiResponse]>; + deleteFiles(query?: BucketQuery): Promise; + exists(): Promise<[boolean]>; + file(name: string, options?: BucketFileOptions): File; + get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]>; + getFiles(query?: BucketQuery): Promise<[File[]]>; + getFilesStream(query?: BucketQuery): ReadStream; + getMetadata(): Promise<[BucketMetadata, ApiResponse]>; + id: string; + makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]>; + makePublic(options?: BucketPrivacyOptions): Promise<[File[]]>; + metadata: BucketMetadata; + name: string; + setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]>; + upload(localPath: string, options?: UploadOptions): Promise<[File]>; + } + + /** + * Bucket configuration. + */ + interface BucketConfig { + coldline?: boolean; + dra?: boolean; + location?: string; + multiRegional?: boolean; + nearline?: boolean; + regional?: boolean; + versioning?: { + enabled?: boolean + }; + } + + /** + * Options for getting a file. + */ + interface BucketFileOptions { + generation?: string | number; + } + + /** + * Options for getting a bucket. + */ + interface BucketGetOptions { + autoCreate?: boolean; + } + + /** + * Bucket metadata. + */ + interface BucketMetadata { + etag?: string; + id?: string; + kind?: string; + location?: string; + metageneration?: string; + name?: string; + projectNumber?: string; + selfLink?: string; + storageClass?: string; + timeCreated?: string; + updated?: string; + } + + /** + * The options for making the bucket private. + */ + interface BucketPrivacyOptions { + includeFiles?: boolean; + force?: boolean; + } + + /** + * Query a bucket. + */ + interface BucketQuery { + autoPaginate?: boolean; + delimiter?: string; + prefix?: string; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + versions?: boolean; + } +} + +declare module "@google-cloud/storage/channel" { + import { ApiResponse } from "@google-cloud/storage/storage"; + + /** + * This class allows you interact with Google Cloud Storage. + */ + class Channel { + stop(): Promise<[ApiResponse]>; + } + + /** + * Channel configuration. + */ + interface ChannelConfig { + address: string; + } +} + +declare module "@google-cloud/storage/file" { + import { ReadStream, WriteStream } from "fs"; + import { Bucket } from "@google-cloud/storage/bucket"; + import { + Acl, + ApiResponse, + DownloadOptions, + ReadStreamOptions, + UploadOptions, + WriteStreamOptions + } from "@google-cloud/storage/storage"; + + /** + * Options for specifying the content length range. + */ + interface ContentLengthRange { + max?: number; + min?: number; + } + + /** + * A file in the cloud. + */ + class File { + acl: Acl; + copy(destination: string | Bucket | File): Promise<[File, ApiResponse]>; + createReadStream(options?: ReadStreamOptions): ReadStream; + createWriteStream(options?: WriteStreamOptions): WriteStream; + delete(): Promise<[ApiResponse]>; + download(options?: DownloadOptions): Promise<[string]>; + exists(): Promise<[boolean]>; + get(): Promise<[File, ApiResponse]>; + getMetadata(): Promise<[FileMetadata, ApiResponse]>; + getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]>; + getSignedUrl(config?: SignedUrlConfig): Promise<[string]>; + makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]>; + makePublic(): Promise<[ApiResponse]>; + move(destination: string | Bucket | File): Promise<[File, ApiResponse]>; + name: string; + save(data: string, options?: WriteStreamOptions): Promise; + setEncryptionKey(encryptionKey: string | Buffer): File; + setMetadata(metadata: FileMetadata): Promise<[ApiResponse]>; + } + + /** + * File metadata. + */ + interface FileMetadata { + contentType?: string; + } + + /** + * Options when setting the file as private. + */ + interface FilePrivateOptions { + strict?: boolean; + } + + /** + * A signed policy allowing a user to upload a file with a POST. + */ + interface SignedPolicy { + base64?: string; + signature?: string; + string?: string; + } + + /** + * Options when obtaining the signed policy. + */ + interface SignedPolicyOptions { + acl?: string; + contentLengthRange?: ContentLengthRange; + equals?: string[] | [string[]]; + expires?: number | string; + max?: number; + min?: number; + startsWith?: string[] | [string[]]; + successRedirect?: string; + successStatus?: string; + } + + /** + * Options when obtaining a temporary signed URL for a file. + */ + interface SignedUrlConfig { + action: string; + cname?: string; + contentMd5?: string; + contentType?: string; + expires?: number | string; + extensionHeaders?: {[key: string]: string}; + promptSaveAs?: string; + responseDisposition?: string; + responseType?: string; + } +} + +declare module "@google-cloud/storage/storage" { + import { ReadStream } from "fs"; + import { Bucket, BucketConfig, BucketQuery } from "@google-cloud/storage/bucket"; + import { Channel } from "@google-cloud/storage/channel"; + import { FileMetadata } from "@google-cloud/storage/file"; + + /** + * Access control list for storage buckets and files. + */ + class Acl extends AclActions { + default: AclEntity; + owners: AclEntity; + readers: AclEntity; + writers: AclEntity; + } + + /** + * Actions that can be performed on all ACL entities, including the root Acl. + */ + class AclActions { + add(options: AclOptions): Promise<[Acl, ApiResponse]>; + delete(options: AclOptions): Promise<[Acl, ApiResponse]>; + get(options: AclOptions): Promise<[Acl, ApiResponse]>; + update(options: AclOptions): Promise<[Acl, ApiResponse]>; + } + + /** + * An object of convenience methods to add or delete reader ACL permissions for a given entity. + */ + class AclEntity extends AclActions { + addAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; + addAllUsers(): Promise<[Acl, ApiResponse]>; + addDomain(entity: string): Promise<[Acl, ApiResponse]>; + addGroup(entity: string): Promise<[Acl, ApiResponse]>; + addProject(entity: string): Promise<[Acl, ApiResponse]>; + addUser(entity: string): Promise<[Acl, ApiResponse]>; + deleteAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; + deleteAllUsers(): Promise<[Acl, ApiResponse]>; + deleteDomain(entity: string): Promise<[Acl, ApiResponse]>; + deleteGroup(entity: string): Promise<[Acl, ApiResponse]>; + deleteProject(entity: string): Promise<[Acl, ApiResponse]>; + deleteUser(entity: string): Promise<[Acl, ApiResponse]>; + } + + /** + * ACL options. + */ + interface AclOptions { + entity?: string; + role?: string; + generation?: number; + } + + /** + * The response object. + */ + interface ApiResponse { + etag?: string; + id?: string; + kind?: string; + location?: string; + metageneration?: string; + name?: string; + projectNumber?: string; + selfLink?: string; + storageClass?: string; + timeCreated?: string; + updated?: string; + } + + /** + * The options when downloading a file. + */ + interface DownloadOptions extends ReadStreamOptions { + destination?: string; + } + + /** + * Options when reading a file stream. + */ + interface ReadStreamOptions { + end?: number; + start?: number; + validation?: string | boolean; + } + + /** + * Options when uploading file to bucket. + */ + interface UploadOptions extends WriteStreamOptions { + destination?: string; + } + + /** + * Options when writing to a file stream. + */ + interface WriteStreamOptions { + gzip?: boolean; + metadata?: FileMetadata; + offset?: number; + predefinedAcl?: string; + private?: boolean; + public?: boolean; + resumable?: boolean; + uri?: string; + validation?: string | boolean; + } + + /** + * The Storage class allows you interact with Google Cloud Storage. + */ + class Storage { + acl: Acl; + bucket(name: string|Bucket): Bucket; + channel(id: string, resourceId: string): Channel; + createBucket(name: string, metadata?: BucketConfig): Promise<[Bucket, ApiResponse]>; + getBuckets(query?: BucketQuery): Promise<[Bucket[]]>; + getBucketsStream(query?: BucketQuery): Promise<[ReadStream]>; + } +} diff --git a/types/google-cloud__storage/tsconfig.json b/types/google-cloud__storage/tsconfig.json new file mode 100644 index 0000000000..51d8bc1368 --- /dev/null +++ b/types/google-cloud__storage/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-cloud__storage-tests.ts" + ] +} \ No newline at end of file diff --git a/types/google-cloud__storage/tslint.json b/types/google-cloud__storage/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/google-cloud__storage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/googlemaps/googlemaps-tests.ts b/types/googlemaps/googlemaps-tests.ts index f57a4e80e0..20d2bc51c8 100644 --- a/types/googlemaps/googlemaps-tests.ts +++ b/types/googlemaps/googlemaps-tests.ts @@ -11,6 +11,7 @@ let map = new google.maps.Map( fullscreenControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, + gestureHandling: "cooperative", scrollwheel: true, zoom: 4 }); diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 1ca49880c9..0e12a8e643 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Maps JavaScript API 3.26 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -95,6 +95,10 @@ declare namespace google.maps { fullscreenControl?: boolean; /** The display options for the Fullscreen control. */ fullscreenControlOptions?: FullscreenControlOptions; + /** + * This setting controls how gestures on the map are handled. + */ + gestureHandling?: GestureHandlingOptions; /** * The heading for aerial imagery in degrees measured clockwise from cardinal * direction North. Headings are snapped to the nearest available angle for @@ -250,6 +254,12 @@ declare namespace google.maps { opened?: boolean; } + export type GestureHandlingOptions = + "cooperative" | + "greedy" | + "none" | + "auto"; + /** Options for the rendering of the pan control. */ export interface PanControlOptions { /** diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 5a2cdd0af4..0f02cd78af 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -51,7 +51,7 @@ export class GraphQLSchema { getQueryType(): GraphQLObjectType; getMutationType(): GraphQLObjectType; getSubscriptionType(): GraphQLObjectType; - getTypeMap(): GraphQLNamedType; + getTypeMap(): { [typeName: string]: GraphQLNamedType }; getType(name: string): GraphQLType; getPossibleTypes(abstractType: GraphQLAbstractType): Array; diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index 3546ac3433..f1da1b35b4 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -1,22 +1,33 @@ - - -var params: ReCaptchaV2.Parameters = { - "sitekey": "mySuperSecretKey", - "theme": "light", - "type": "image", - "size": "normal", - "tabindex": 5, - "callback": (response: string) => { }, +const params: ReCaptchaV2.Parameters = { + sitekey: "mySuperSecretKey", + theme: "light", + type: "image", + size: "normal", + tabindex: 5, + callback: (response: string) => { }, "expired-callback": () => { }, -} +}; -var id1: number = grecaptcha.render("foo"); -var id2: number = grecaptcha.render("foo", params); -var id3: number = grecaptcha.render(document.getElementById("foo")); -var id4: number = grecaptcha.render(document.getElementById("foo"), params); +const size1: ReCaptchaV2.Size = "compact"; +const size2: ReCaptchaV2.Size = "invisible"; +const size3: ReCaptchaV2.Size = "normal"; + +const badge1: ReCaptchaV2.Badge = "bottomleft"; +const badge2: ReCaptchaV2.Badge = "bottomright"; +const badge3: ReCaptchaV2.Badge = "inline"; + +const invisibleParams: ReCaptchaV2.Parameters = { + sitekey: "siteKey", + badge: badge1, +}; + +const id1: number = grecaptcha.render("foo"); +const id2: number = grecaptcha.render("foo", params); +const id3: number = grecaptcha.render(document.getElementById("foo")); +const id4: number = grecaptcha.render(document.getElementById("foo"), params); // response takes a number and returns a string -var response1: string = grecaptcha.getResponse(id1); +const response1: string = grecaptcha.getResponse(id1); // reset takes a number grecaptcha.reset(id1); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index 26f4e69507..59d1fa6699 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -1,85 +1,90 @@ // Type definitions for Google Recaptcha 2.0 // Project: https://www.google.com/recaptcha -// Definitions by: Kristof Mattei , Martin Costello +// Definitions by: Kristof Mattei , Martin Costello , Ruslan Arkhipau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var grecaptcha: ReCaptchaV2.ReCaptcha; -declare namespace ReCaptchaV2 -{ - class ReCaptcha - { +declare namespace ReCaptchaV2 { + class ReCaptcha { /** - * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. - * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. - * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. - * @return the ID of the newly created widget. - **/ + * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. + * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. + * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @return the ID of the newly created widget. + */ render(container: (string | HTMLElement), parameters?: Parameters): number; /** - * Resets the reCAPTCHA widget. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - **/ + * Resets the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + */ reset(opt_widget_id?: number): void; /** - * Gets the response for the reCAPTCHA widget. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - * @return the response of the reCAPTCHA widget. - **/ + * Gets the response for the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + * @return the response of the reCAPTCHA widget. + */ getResponse(opt_widget_id?: number): string; /** - * Programatically invoke the reCAPTCHA check. Used if the invisible reCAPTCHA is on a div instead of a button. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - **/ + * Programatically invoke the reCAPTCHA check. Used if the invisible reCAPTCHA is on a div instead of a button. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + */ execute(opt_widget_id?: number): void; } type Theme = "light" | "dark"; type Type = "image" | "audio"; - type Size = "normal" | "compact"; + type Size = "normal" | "compact" | "invisible"; + type Badge = "bottomright" | "bottomleft" | "inline"; - interface Parameters - { + interface Parameters { /** - * Your sitekey. - **/ + * Your sitekey. + */ sitekey: string; /** - * Optional. The color theme of the widget. - * Accepted values: "light", "dark" - * @default "light" - * @type {Theme} - **/ + * Optional. The color theme of the widget. + * Accepted values: "light", "dark" + * @default "light" + * @type {Theme} + */ theme?: Theme; /** - * Optional. The type of CAPTCHA to serve. - * Accepted values: "audio", "image" - * @default "image" - * @type {Type} - **/ + * Optional. The type of CAPTCHA to serve. + * Accepted values: "audio", "image" + * @default "image" + * @type {Type} + */ type?: Type; /** - * Optional. The size of the widget. - * Accepted values: "compact", "normal" - * @default "compact" - * @type {Size} - */ + * Optional. The size of the widget. + * Accepted values: "compact", "normal", "invisible". + * @default "compact" + * @type {Size} + */ size?: Size; /** - * Optional. The tabindex of the widget and challenge. - * If other elements in your page use tabindex, it should be set to make user navigation easier. - **/ + * Optional. The tabindex of the widget and challenge. + * If other elements in your page use tabindex, it should be set to make user navigation easier. + */ tabindex?: number; /** - * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. - * The user's response, g-recaptcha-response, will be the input for your callback function. - **/ - callback?: (response: string) => void; + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + */ + callback?(response: string): void; /** - * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. - **/ + * Optional. The badge location for g-recaptcha with size of "invisible". + * + * @default "bottomright" + * @type {Badge} + */ + badge?: Badge; + /** + * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + */ // Notice to the reader // I need to surround this object with quotes, this will however break intellisense in VS 2013. - "expired-callback"?: () => void; + "expired-callback"?(): void; } } diff --git a/types/grecaptcha/tslint.json b/types/grecaptcha/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/grecaptcha/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/h2o2/h2o2-tests.ts b/types/h2o2/h2o2-tests.ts new file mode 100644 index 0000000000..f8e88c5c9b --- /dev/null +++ b/types/h2o2/h2o2-tests.ts @@ -0,0 +1,165 @@ +import http = require("http"); +import * as Boom from 'boom'; +import * as Hapi from 'hapi'; +import * as Wreck from 'wreck'; +import h2o2 = require('h2o2'); + +// https://github.com/hapijs/h2o2#manual-loading + +const server = new Hapi.Server({}); + +server.register({ + register: h2o2 +}, function (err) { + + if (err) { + console.log('Failed to load h2o2'); + } + + server.start(function (err) { + + console.log('Server started at: ' + server.info!.uri); + }); +}); + +// https://github.com/hapijs/h2o2#replyproxyoptions + +const handler: Hapi.RouteHandler = function (request, reply) { + + return reply.proxy({ host: 'example.com', port: 80, protocol: 'http' }); +}; + +// https://github.com/hapijs/h2o2#using-the-host-port-protocol-options + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + host: '10.33.33.1', + port: '443', + protocol: 'https' + } + } +}); + +// https://github.com/hapijs/h2o2#using-the-uri-option + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/that/has?what=you&want=todo' + } + } +}); + +// https://github.com/hapijs/h2o2#custom-uri-template-values + +server.route({ + method: 'GET', + path: '/foo', + handler: { + proxy: { + uri: '{protocol}://{host}:{port}/go/to/{path}' + } + } +}); + +server.route({ + method: 'GET', + path: '/foo/{bar}', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/some/path/to/{bar}' + } + } +}); + +// https://github.com/hapijs/h2o2#using-the-mapuri-and-onresponse-options + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + mapUri: function (request, callback) { + + console.log('doing some aditional stuff before redirecting'); + callback(null, 'https://some.upstream.service.com/'); + }, + onResponse: function (err, res, request, reply, settings, ttl) { + + console.log('receiving the response from the upstream.'); + Wreck.read(res, { json: true }, function (err, payload) { + + console.log('some payload manipulation if you want to.') + reply(payload).headers = res.headers; + }); + } + } + } +}); + +/** + * test code added in additional to code in docs. Demonstrates that for the moment + * you need flat + * objects with typing along the way to benefit from typescript catching + * misspelt, or unsupported keys. + * This is because of an unknown reason. Expecting this to work because: + * "Object literals get special treatment and undergo excess + * property checking when assigning them to other variables, or passing them + * as arguments", see github.com/Microsoft/TypeScript + */ + +var proxyOptions: h2o2.ProxyHandlerOptions = { + host: '10.33.33.1', + port: '443', + protocol: 'https' // errors correctly if misspelt +} + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + host: '10.33.33.1', + port: '443', + BAD_protocol: 'https' // TODO change typings to fix this / submit bug report + } + } +}) + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/that/has?what=you&want=todo' + } + } +}) + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + mapUri: function (request: Hapi.Request, callback: (err: null | Boom.BoomError, value: string) => void) { + + console.log('doing some aditional stuff before redirecting'); + callback(null, 'https://some.upstream.service.com/'); + }, + onResponse: function (err: null | Boom.BoomError, res: http.IncomingMessage, request: Hapi.Request, reply: Hapi.ReplyWithContinue, settings: h2o2.ProxyHandlerOptions, ttl: number) { + + console.log('receiving the response from the upstream.'); + Wreck.read(res, { json: true }, function (err: null | Boom.BoomError, payload: any) { + + console.log('some payload manipulation if you want to.') + reply(payload).headers = res.headers; + }); + } + } + } +}); diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts new file mode 100644 index 0000000000..a1a3680e5c --- /dev/null +++ b/types/h2o2/index.d.ts @@ -0,0 +1,91 @@ +// Type definitions for h2o2 5.4 +// Project: https://github.com/hapijs/catbox +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import http = require("http"); +import * as hapi from 'hapi'; +import * as Boom from 'boom'; + +declare namespace H2o2 { + /** Proxy handler options */ + export interface ProxyHandlerOptions { + /** host - upstream service host to proxy requests to. It will have the same path as the client request. */ + host?: string; + /** port - upstream service port. */ + port?: number | string; + /** protocol - protocol to use when making the request to the proxied host: */ + protocol?: 'http' | 'https'; + /** uri - absolute URI used instead of host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri. */ + uri?: string; + /** passThrough - if set to true, it forwards the headers from the client to the upstream service, headers sent from the upstream service will also be forwarded to the client. Defaults to false. */ + passThrough?: boolean; + /** localStatePassThrough - if set tofalse, any locally defined state is removed from incoming requests before being sent to the upstream service. This value can be overridden on a per state basis via the server.state()``passThrough option. Defaults to false */ + localStatePassThrough?: boolean; + /** acceptEncoding - if set to false, does not pass-through the 'Accept-Encoding' HTTP header which is useful for the onResponse post-processing to avoid receiving an encoded response. Can only be used together with passThrough. Defaults to true (passing header). */ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. If set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true. */ + rejectUnauthorized?: boolean; + /** xforward - if set to true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto', 'X-Forwarded-Host' headers when making a request to the proxied upstream endpoint. Defaults to false. */ + xforward?: boolean; + /** redirects - the maximum number of HTTP redirections allowed to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false. */ + redirects?: number | false; + /** timeout - number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes). */ + timeout?: number; + /** mapUri - a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function (request, callback) where: + * @param request - is the incoming request object. + * @param callback - is function (err, uri, headers) where: + * @param err - internal error condition. TODO: check this is of type BoomError or just Error. + * @param uri - the absolute proxy URI. + * @param headers - optional object where each key is an HTTP request header and the value is the header content. + */ + mapUri?: (request: hapi.Request, callback: (err: null | Boom.BoomError, uri: string, headers?: { [key: string]: string }) => void) => void; + /** + * onResponse - a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function (err, res, request, reply, settings, ttl) where: + * @param err - internal or upstream error returned from attempting to contact the upstream proxy. TODO: check this is of type BoomError or just Error. + * @param res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). + * @param request - is the incoming request object. + * @param reply - the reply interface function. + * @param settings - the proxy handler configuration. + * @param ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'. + */ + onResponse?: (err: null | Boom.BoomError, + res: http.IncomingMessage, + req: hapi.Request, + reply: hapi.ReplyWithContinue, // TODO, check it has continue + settings: ProxyHandlerOptions, + ttl: number) => void; + /** ttl - if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided). */ + ttl?: 'upstream'; + /** agent - a node http(s) agent to be used for connections to upstream server. @see {@link https://nodejs.org/api/http.html#http_class_http_agent} */ + agent?: http.Agent; + /** maxSockets - sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity. */ + maxSockets?: false | number; + } +} + +declare module 'hapi' { + /** + * As one of the handlers for hapi, it is used through the route configuration object. + * [see docs](https://github.com/hapijs/h2o2#usage) + */ + interface RouteHandlerPlugins { + proxy?: H2o2.ProxyHandlerOptions; + } + + interface Base_Reply { + /** + * Proxies the request to an upstream endpoint + * @param options an object including the same keys and restrictions defined by the [route proxy handler options](https://github.com/hapijs/h2o2#options). + * [see docs](https://github.com/hapijs/h2o2#replyproxyoptions) + */ + proxy(options: H2o2.ProxyHandlerOptions): void; + } +} + +declare var H2o2: hapi.PluginFunction<{}>; + +export = H2o2; diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json new file mode 100644 index 0000000000..1abbac7fb0 --- /dev/null +++ b/types/h2o2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "h2o2-tests.ts" + ] +} \ No newline at end of file diff --git a/types/handsontable/index.d.ts b/types/handsontable/index.d.ts index 23f99e60a4..165d872e8f 100644 --- a/types/handsontable/index.d.ts +++ b/types/handsontable/index.d.ts @@ -79,7 +79,8 @@ declare namespace __Handsontable { selectCellByProp(row: number, prop: string, endRow?: number, endProp?: string, scrollToCell?: boolean): boolean; setCellMeta(row: number, col: number, key: string, val: string): void; setCellMetaObject(row: number, col: number, prop: Object): void; - setDataAtCell(row: number|any[], col: number, value: string, source?: string): void; + setDataAtCell(row: number, col: number, value: string, source?: string): void; + setDataAtCell(changes: Array<[number, number, any]>): void; setDataAtRowProp(row: number|any[], prop: string, value: string, source?: string): void; spliceCol(col: number, index: number, amount: number, elements?: any): void; spliceRow(row: number, index: number, amount: number, elements?: any): void; @@ -218,7 +219,7 @@ declare namespace Handsontable { // hooks afterAutofillApplyValues?(startArea: any[], entireArea: any[]): void; afterCellMetaReset?(): void; - afterChange?(changes: any[], source: string): void; + afterChange?(changes: Array<[number, number|string, any, any]>, source?: string): void; afterChangesObserved?(): void; afterColumnMove?(startColumn: number, endColumn: number): void; afterColumnResize?(currentColumn: number, newSize: number, isDoubleClick: boolean): void; @@ -241,6 +242,7 @@ declare namespace Handsontable { afterInit?(): void; afterLoadData?(firstTime: boolean): void; afterMomentumScroll?(): void; + afterOnCellCornerDblClick?(event: Object): void; afterOnCellCornerMouseDown?(event: Object): void; afterOnCellMouseDown?(event: Object, coords: Object, TD: Element): void; afterOnCellMouseOver?(event: Object, coords: Object, TD: Element): void; @@ -412,6 +414,7 @@ declare namespace Handsontable { getWindowScrollTop(): number; outerHeight(element: HTMLElement): number; hasClass(element: HTMLElement, className: string): boolean | undefined; + empty(element: HTMLElement): void; } interface ArrayMapper { diff --git a/types/handsontable/test/global.ts b/types/handsontable/test/global.ts index d4516d80e1..331f62759d 100644 --- a/types/handsontable/test/global.ts +++ b/types/handsontable/test/global.ts @@ -122,7 +122,7 @@ function test_HandsontableInit() { // Hooks afterAutofillApplyValues: () => {return; }, afterCellMetaReset: () => {return; }, - afterChange: () => {return; }, + afterChange: (changes) => {return; }, afterChangesObserved: () => {return; }, afterColumnMove: () => {return; }, afterColumnResize: () => {return; }, @@ -145,6 +145,7 @@ function test_HandsontableInit() { afterInit: () => {return; }, afterLoadData: () => {return; }, afterMomentumScroll: () => {return; }, + afterOnCellCornerDblClick: () => {return; }, afterOnCellCornerMouseDown: () => {return; }, afterOnCellMouseDown: () => {return; }, afterOnCellMouseOver: () => {return; }, @@ -276,6 +277,7 @@ function test_HandsontableMethods() { hot.setCellMeta(123, 123, 'foo', 'foo'); hot.setCellMetaObject(123, 123, {}); hot.setDataAtCell(123, 123, 'foo', 'foo'); + hot.setDataAtCell([[123, 123, 'foo'], [123, 123, 'foo']]); hot.setDataAtRowProp(123, 'foo', 'foo', 'foo'); hot.spliceCol(123, 123, 123, 'foo'); hot.spliceRow(123, 123, 123, 'foo'); @@ -290,6 +292,7 @@ function test_HandsontableMethods() { Handsontable.renderers.NumericRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.renderers.TextRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => { return; }); + Handsontable.Dom.empty(new HTMLElement()); } class MyCustomHotPlugin extends Handsontable.plugins.BasePlugin { diff --git a/types/handsontable/test/module.ts b/types/handsontable/test/module.ts index 5d0ef22655..a67ab6942d 100644 --- a/types/handsontable/test/module.ts +++ b/types/handsontable/test/module.ts @@ -124,7 +124,7 @@ function test_HandsontableInit() { // Hooks afterAutofillApplyValues: () => {return; }, afterCellMetaReset: () => {return; }, - afterChange: () => {return; }, + afterChange: (changes) => {return; }, afterChangesObserved: () => {return; }, afterColumnMove: () => {return; }, afterColumnResize: () => {return; }, @@ -147,6 +147,7 @@ function test_HandsontableInit() { afterInit: () => {return; }, afterLoadData: () => {return; }, afterMomentumScroll: () => {return; }, + afterOnCellCornerDblClick: () => {return; }, afterOnCellCornerMouseDown: () => {return; }, afterOnCellMouseDown: () => {return; }, afterOnCellMouseOver: () => {return; }, @@ -278,6 +279,7 @@ function test_HandsontableMethods() { hot.setCellMeta(123, 123, 'foo', 'foo'); hot.setCellMetaObject(123, 123, {}); hot.setDataAtCell(123, 123, 'foo', 'foo'); + hot.setDataAtCell([[123, 123, 'foo'], [123, 123, 'foo']]); hot.setDataAtRowProp(123, 'foo', 'foo', 'foo'); hot.spliceCol(123, 123, 123, 'foo'); hot.spliceRow(123, 123, 123, 'foo'); @@ -292,6 +294,7 @@ function test_HandsontableMethods() { Handsontable.renderers.NumericRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.renderers.TextRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => { return; }); + Handsontable.Dom.empty(new HTMLElement()); } class MyCustomHotPlugin extends Handsontable.plugins.BasePlugin { diff --git a/types/hapi-auth-basic/hapi-auth-basic-tests.ts b/types/hapi-auth-basic/hapi-auth-basic-tests.ts new file mode 100644 index 0000000000..7f78fe9f65 --- /dev/null +++ b/types/hapi-auth-basic/hapi-auth-basic-tests.ts @@ -0,0 +1,42 @@ +// from https://github.com/hapijs/hapi-auth-basic#hapi-auth-basic + +import Bcrypt = require('bcrypt'); +import Basic = require('hapi-auth-basic'); +import * as Hapi from 'hapi'; + +const server = new Hapi.Server(); + +interface User { + username: string; + password: string; + name: string; + id: string; +} + +const users: {[index: string]: User} = { + john: { + username: 'john', + password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' + name: 'John Doe', + id: '2133d32a' + } +}; + +const validate: Basic.ValidateFunc = function (request, username, password, callback) { + + const user = users[username]; + if (!user) { + return callback(null, false); + } + + Bcrypt.compare(password, user.password, (err, isValid) => { + + callback(err, isValid, { id: user.id, name: user.name }); + }); +}; + +server.register(Basic, (err) => { + + server.auth.strategy('simple', 'basic', { validateFunc: validate }); + server.route({ method: 'GET', path: '/', config: { auth: 'simple' } }); +}); diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts new file mode 100644 index 0000000000..23b06de111 --- /dev/null +++ b/types/hapi-auth-basic/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for hapi 4.2 +// Project: https://github.com/hapijs/hapi-auth-basic +// Definitions by: AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Hapi from 'hapi'; + +declare namespace Basic { + interface ValidateFuncCallback { + (err: Error | null, isValid: boolean, userCredentials?: any): void; + } + + interface ValidateFunc { + (request: Hapi.Request, username: string, password: string, callback: ValidateFuncCallback): void; + } +} + +declare var Basic: Hapi.PluginFunction<{}>; + +export = Basic; diff --git a/types/hapi-auth-basic/tsconfig.json b/types/hapi-auth-basic/tsconfig.json new file mode 100644 index 0000000000..9e26f11c47 --- /dev/null +++ b/types/hapi-auth-basic/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-auth-basic-tests.ts" + ] +} diff --git a/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts b/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts index d0bf1b8688..640706f856 100644 --- a/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts +++ b/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts @@ -29,13 +29,14 @@ function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.V } server.register(hapiAuthJwt2, err => { - server.auth.strategy('jwt', 'jwt', { + const options: hapiAuthJwt2.Options = { key: 'NeverShareYourSecret', validateFunc: validate, verifyOptions: { algorithms: ['HS256'] } - }); + }; + server.auth.strategy('jwt', 'jwt', options); }); server.start(); diff --git a/types/hapi-auth-jwt2/index.d.ts b/types/hapi-auth-jwt2/index.d.ts index c12a1f8c04..2e5826e044 100644 --- a/types/hapi-auth-jwt2/index.d.ts +++ b/types/hapi-auth-jwt2/index.d.ts @@ -2,125 +2,129 @@ // Project: http://github.com/dwyl/hapi-auth-jwt2 // Definitions by: Warren Seymour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Request, Response} from 'hapi'; +import {Request, Response, PluginFunction} from 'hapi'; -/** - * A key lookup function - * - * @param decoded the *decoded* but *unverified* JWT received from client - * @param callback the key lookup callback - */ -export type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void; - -/** - * Called when key lookup function has completed - * - * @param err an internal error - * @param key the secret key - * @param extraInfo any additional information that you would like - * to use in `validateFunc` which can be accessed via - * `request.plugins['hapi-auth-jwt2'].extraInfo` - */ -export type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void; - -/** - * Called when Validation has completed - * - * @param err an internal error - * @param valid `true` if the JWT was valid, otherwise `false` - * @param credentials alternative credentials to be set instead of `decoded` - */ -export type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void; - -/** - * Options passed to `hapi.auth.strategy` when this plugin is used - */ -export interface Options { - /** - * The secret key used to check the signature of the token *or* a *key lookup function* - */ - key?: string | KeyLookup; - - /** - * The function which is run once the Token has been decoded - * - * @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization* - * @param request the original *request* received from the client - * @param callback the validation callback - */ - validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void; - - /** - * Settings to define how tokens are verified by the jsonwebtoken library - */ - verifyOptions?: { +declare namespace hapiAuthJwt2 { /** - * Ignore expired tokens + * A key lookup function + * + * @param decoded the *decoded* but *unverified* JWT received from client + * @param callback the key lookup callback */ - ignoreExpiration?: boolean; + type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void; /** - * Do not enforce token audience + * Called when key lookup function has completed + * + * @param err an internal error + * @param key the secret key + * @param extraInfo any additional information that you would like + * to use in `validateFunc` which can be accessed via + * `request.plugins['hapi-auth-jwt2'].extraInfo` */ - audience?: boolean; + type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void; /** - * Do not require the issuer to be valid + * Called when Validation has completed + * + * @param err an internal error + * @param valid `true` if the JWT was valid, otherwise `false` + * @param credentials alternative credentials to be set instead of `decoded` */ - issuer?: boolean; + type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void; /** - * List of allowed algorithms + * Options passed to `hapi.auth.strategy` when this plugin is used */ - algorithms?: string[]; - }; + interface Options { + /** + * The secret key used to check the signature of the token *or* a *key lookup function* + */ + key?: string | KeyLookup; - /** - * function called to decorate the response with authentication headers - * before the response headers or payload is written - * - * @param request the Request object - * @param reply is called if an error occurred - */ - responseFunc?(request: Request, reply: (err: any, response: Response) => void): void; + /** + * The function which is run once the Token has been decoded + * + * @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization* + * @param request the original *request* received from the client + * @param callback the validation callback + */ + validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void; - /** - * If you prefer to pass your token via url, simply add a token url - * parameter to your request or use a custom parameter by setting `urlKey. - * To disable the url parameter set urlKey to `false` or ''. - * @default 'token' - */ - urlKey?: string | boolean; + /** + * Settings to define how tokens are verified by the jsonwebtoken library + */ + verifyOptions?: { + /** + * Ignore expired tokens + */ + ignoreExpiration?: boolean; - /** - * If you prefer to set your own cookie key or your project has a cookie - * called 'token' for another purpose, you can set a custom key for your - * cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies - * set cookieKey to `false` or ''. - * @default 'token' - */ - cookieKey?: string | boolean; + /** + * Do not enforce token audience + */ + audience?: boolean; - /** - * If you want to set a custom key for your header token use the - * `headerKey` option. To disable header token set headerKey to `false` or - * ''. - * @default 'authorization' - */ - headerKey?: string | boolean; + /** + * Do not require the issuer to be valid + */ + issuer?: boolean; - /** - * Allow custom token type, e.g. `Authorization: 12345678` - */ - tokenType?: string; + /** + * List of allowed algorithms + */ + algorithms?: string[]; + }; - /** - * Set to `true` to receive the complete token (`decoded.header`, - * `decoded.payload` and `decoded.signature`) as decoded argument to key - * lookup and `verifyFunc` callbacks (*not `validateFunc`*) - * @default false - */ - complete?: boolean; + /** + * function called to decorate the response with authentication headers + * before the response headers or payload is written + * + * @param request the Request object + * @param reply is called if an error occurred + */ + responseFunc?(request: Request, reply: (err: any, response: Response) => void): void; + + /** + * If you prefer to pass your token via url, simply add a token url + * parameter to your request or use a custom parameter by setting `urlKey. + * To disable the url parameter set urlKey to `false` or ''. + * @default 'token' + */ + urlKey?: string | boolean; + + /** + * If you prefer to set your own cookie key or your project has a cookie + * called 'token' for another purpose, you can set a custom key for your + * cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies + * set cookieKey to `false` or ''. + * @default 'token' + */ + cookieKey?: string | boolean; + + /** + * If you want to set a custom key for your header token use the + * `headerKey` option. To disable header token set headerKey to `false` or + * ''. + * @default 'authorization' + */ + headerKey?: string | boolean; + + /** + * Allow custom token type, e.g. `Authorization: 12345678` + */ + tokenType?: string; + + /** + * Set to `true` to receive the complete token (`decoded.header`, + * `decoded.payload` and `decoded.signature`) as decoded argument to key + * lookup and `verifyFunc` callbacks (*not `validateFunc`*) + * @default false + */ + complete?: boolean; + } } -export default function hapiAuthJwt2(): void; +declare var hapiAuthJwt2: PluginFunction<{}>; + +export = hapiAuthJwt2; diff --git a/types/hapi-decorators/hapi-decorators-tests.ts b/types/hapi-decorators/hapi-decorators-tests.ts index 49a112152a..2a6f2df5b3 100644 --- a/types/hapi-decorators/hapi-decorators-tests.ts +++ b/types/hapi-decorators/hapi-decorators-tests.ts @@ -4,7 +4,7 @@ import { controller, get, post, put, cache, config, route, validate, Controller @controller('/test') class TestController implements Controller { baseUrl: string; - routes: () => hapi.IRouteConfiguration[]; + routes: () => hapi.RouteConfiguration[]; @get('/') @config({ @@ -16,22 +16,22 @@ class TestController implements Controller { @validate({ payload: false }) - getHandler(request: hapi.Request, reply: hapi.IReply) { + getHandler(request: hapi.Request, reply: hapi.ReplyNoContinue) { reply({ success: true }); } @post('/') - postHandler(request: hapi.Request, reply: hapi.IReply) { + postHandler(request: hapi.Request, reply: hapi.ReplyNoContinue) { reply({ success: true }); } @put('/{id}') - putHandler(request: hapi.Request, reply: hapi.IReply) { + putHandler(request: hapi.Request, reply: hapi.ReplyNoContinue) { reply({ success: true }); } @route('delete', '/{id}') - deleteHandler(request: hapi.Request, reply: hapi.IReply) { + deleteHandler(request: hapi.Request, reply: hapi.ReplyNoContinue) { reply({ success: true }); } } @@ -50,7 +50,7 @@ class SimpleTestController implements Controller { } baseUrl: string; - routes: () => hapi.IRouteConfiguration[]; + routes: () => hapi.RouteConfiguration[]; } server.route(new SimpleTestController('bar').routes()); diff --git a/types/hapi-decorators/index.d.ts b/types/hapi-decorators/index.d.ts index fc32ae8ad5..2933945e64 100644 --- a/types/hapi-decorators/index.d.ts +++ b/types/hapi-decorators/index.d.ts @@ -4,12 +4,13 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as hapi from 'hapi'; +import * as Joi from 'joi'; interface ControllerStatic { new (...args: any[]): Controller; } export interface Controller { baseUrl: string; - routes: () => hapi.IRouteConfiguration[]; + routes: () => hapi.RouteConfiguration[]; } export function controller(baseUrl: string): (target: ControllerStatic) => void; interface IRouteSetup { @@ -28,61 +29,9 @@ export const put: IRouteConfig; // export const delete: IRouteConfig; export const patch: IRouteConfig; export const all: IRouteConfig; -export function config(config: hapi.IRouteAdditionalConfigurationOptions): (target: any, key: any, descriptor: any) => any; -interface IValidateConfig { - /** validation rules for incoming request headers.Values allowed: - * trueany headers allowed (no validation performed).This is the default. - falseno headers allowed (this will cause all valid HTTP requests to fail). - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the request headers. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. - */ - headers?: boolean | hapi.IJoi | hapi.IValidationFunction; - /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: - trueany path parameters allowed (no validation performed).This is the default. - falseno path variables allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the path parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - params?: boolean | hapi.IJoi | hapi.IValidationFunction; - /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: - trueany query parameters allowed (no validation performed).This is the default. - falseno query parameters allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the query parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - query?: boolean | hapi.IJoi | hapi.IValidationFunction; - /** validation rules for an incoming request payload (request body).Values allowed: - trueany payload allowed (no validation performed).This is the default. - falseno payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the payload object. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - payload?: boolean | hapi.IJoi | hapi.IValidationFunction; - /** an optional object with error fields copied into every validation error response. */ - errorFields?: any; - /** determines how to handle invalid requests.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'log the error but continue processing the request. - 'ignore'take no action. - OR a custom error handler function with the signature 'function(request, reply, source, error)` where: - requestthe request object. - replythe continuation reply interface. - sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). - errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction?: string | hapi.IRouteFailFunction; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; -} -export function validate(config: IValidateConfig): (target: any, key: any, descriptor: any) => any; +export function config(config: hapi.RouteAdditionalConfigurationOptions): (target: any, key: any, descriptor: any) => any; + +export function validate(config: hapi.RouteValidationConfigurationObject): (target: any, key: any, descriptor: any) => any; interface ICacheConfig { privacy?: string; expiresIn?: number; diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 3715fef37c..3567e50c34 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,2473 +1,2599 @@ -// Type definitions for hapi 16.0 -// Project: http://github.com/spumko/hapi -// Definitions by: Jason Swearingen +// Type definitions for hapi 16.1 +// Project: https://github.com/hapijs/hapi +// Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -// Note/Disclaimer: This .d.ts was created against hapi v8.x but has been incrementally upgraded to 13.x. Some newer features/changes may be missing. YMMV. +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + * + * + * Removal of IPromise replaced with Promise + * Removal of IReplyStrict<> + * Removal of IReply replaced with different interfaces like: + * ReplyWithContinue + * ReplyNoContinue, etc. + * Renaming of all interfaces to remove preceding I in preparation of dtslint + */ /// -import http = require("http"); -import stream = require("stream"); import Events = require("events"); +import stream = require("stream"); +import http = require("http"); +import https = require("https"); import url = require("url"); +import zlib = require("zlib"); +import domain = require("domain"); -export interface IDictionary { - [key: string]: T; -} +import * as Boom from 'boom'; +import { + ValidationOptions as JoiValidationOptions, + Schema as JoiValidationObject, +} from 'joi'; -export interface IHeaderOptions { - append?: boolean; - separator?: string; - override?: boolean; - duplicate?: boolean; -} +import * as Catbox from 'catbox'; +import {MimosOptions} from 'mimos'; +import Podium = require('podium'); +import * as Shot from 'shot'; -/** Boom Module for errors. https://github.com/hapijs/boom - * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ -export interface IBoom extends Error { - /** if true, indicates this is a Boom object instance. */ - isBoom: boolean; - /** convenience bool indicating status code >= 500. */ - isServer: boolean; - /** the error message. */ - message: string; - /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ - output: { - /** the HTTP status code (typically 4xx or 5xx). */ - statusCode: number; - /** an object containing any HTTP headers where each key is a header name and value is the header content. */ - headers: IDictionary; - /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ - payload: { - /** the HTTP status code, derived from error.output.statusCode. */ - statusCode: number; - /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ - error: string; - /** the error message derived from error.message. */ - message: string; - }; - }; - /** reformat()rebuilds error.output using the other object properties. */ - reformat(): void; -} - -/** cache functionality via the "CatBox" module. */ -export interface ICatBoxCacheOptions { - /** a prototype function or catbox engine object. */ - engine: any; - /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ - name?: string; - /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ - shared?: boolean; -} - -/** policy configuration for the "CatBox" module and server method options. */ -export interface ICatBoxCachePolicyOptions { - /** the cache name configured in server.cache. Defaults to the default cache. */ - cache?: string; - /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ - segment?: string; - /** if true, allows multiple cache provisions to share the same segment. Default to false. */ - shared?: boolean; - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ - expiresIn?: number; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. */ - expiresAt?: number; - /** a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. */ - generateFunc?: Function; - /** number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. */ - staleIn?: number; - /** number of milliseconds to wait before checking if an item is stale. */ - staleTimeout?: number; - /** number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ - generateTimeout?: number; - /** if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true */ - dropOnError?: boolean; - /** if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */ - generateOnReadError?: boolean; - /** if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. */ - generateIgnoreWriteError?: boolean; - /** number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). */ - pendingGenerateTimeout?: number; -} - -/** Any connections configuration server defaults can be included to override and customize the individual connection. */ -export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { - /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ - host?: string; - /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ - address?: string; - /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ - port?: string | number; - /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ - uri?: string; - /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ - listener?: any; - /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ - autoListen?: boolean; - /** caching headers configuration: */ - cache?: { - /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ - statuses: number[]; - }; - /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ - labels?: string | string[]; - /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; -} - -export interface IConnectionConfigurationServerDefaults { - /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ - app?: any; - /** if false, response content encoding is disabled. Defaults to true */ - compression?: boolean; - /** connection load limits configuration where: */ - load?: { - /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxHeapUsedBytes: number; - /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxRssBytes: number; - /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxEventLoopDelay: number; - }; - /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ - plugins?: any; - /** controls how incoming request URIs are matched against the routing table: */ - router?: { - /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ - isCaseSensitive: boolean; - /** removes trailing slashes on incoming paths. Defaults to false. */ - stripTrailingSlash: boolean; - }; - /** a route options object used to set the default configuration for every route. */ - routes?: IRouteAdditionalConfigurationOptions; - state?: IServerState; -} - -/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ -export interface IServerOptions { - /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: any; - /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: - a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). - a configuration object with the following options: - enginea prototype function or catbox engine object. - namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. - sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - other options passed to the catbox strategy used. - an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ - cache?: string | ICatBoxCacheOptions | ICatBoxCacheOptions[] | any; - /** sets the default connections configuration which can be overridden by each connection where: */ - connections?: IConnectionConfigurationServerDefaults; - /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ - debug?: boolean | { - /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ - log: string[]; - /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ - request: string[]; - }; - /** file system related settings*/ - files?: { - /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ - etagsCacheMaxSize?: number; - }; - /** process load monitoring*/ - load?: { - /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ - sampleInterval?: number; - }; - - /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ - mime?: any; - /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ - minimal?: boolean; - /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ - plugins?: IDictionary; -} - -export interface IServerViewCompile { - (template: string, options: any): void; - (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; -} - -export interface IServerViewsAdditionalOptions { - /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ - path?: string; - /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). - */ - partialsPath?: string; - /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ - helpersPath?: string; - /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ - relativeTo?: string; - - /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ - layout?: boolean | string; - /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ - layoutPath?: string; - /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ - layoutKeywork?: string; - /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ - encoding?: string; - /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ - isCached?: boolean; - /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ - allowAbsolutePaths?: boolean; - /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ - allowInsecureAccess?: boolean; - /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ - compileOptions?: any; - /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ - runtimeOptions?: any; - /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ - contentType?: string; - /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ - compileMode?: string; - /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ - context?: any; -} - -export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { - /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. - * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ - module: { - compile?(template: any, options: any): (context: any, options: any) => void; - compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; - }; -} - -/**Initializes the server views manager - var Hapi = require('hapi'); - var server = new Hapi.Server(); - - server.views({ -engines: { -html: require('handlebars'), -jade: require('jade') -}, -path: '/static/templates' -}); - When server.views() is called within a plugin, the views manager is only available to plugins methods. - */ -export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { - /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ - engines: IDictionary | IServerViewsEnginesOptions; - /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ - defaultExtension?: string; -} - -export interface IReplyMethods { - /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. - * The data argument is only used for passing back authentication data and is ignored elsewhere. */ - continue(credentialData?: any): void; - - /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ - file(/** the file path. */ - path: string, - /** optional settings: */ - options?: { - /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /** specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ - lookupCompressed: boolean; - }): void; - /** Concludes the handler activity by returning control over to the router with a templatized view response. - the response flow control rules apply. */ - view(/** the template filename and path, relative to the templates path configured via the server views manager. */ - template: string, - /** optional object used by the template to render context-specific result. Defaults to no context {}. */ - context?: {}, - /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ - options?: any): Response; - /** Sets a header on the response */ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed - The response flow control rules do not apply. */ - close(options?: { - /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ - end?: boolean; - }): void; - /** Proxies the request to an upstream endpoint. - the response flow control rules do not apply. */ - - proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ - options: IProxyHandlerConfig): void; - /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). - he response flow control rules apply. */ - redirect(uri: string): ResponseRedirect; - - /** Replies with the specified response */ - response(result: any): Response; - - /** Sets a cookie on the response */ - state(name: string, value: any, options?: any): void; - - /** Clears a cookie on the response */ - unstate(name: string, options?: any): void; -} - -/** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - result an optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ -export interface IReply extends IReplyMethods { - ( - err: Error, - result?: string | number | boolean | Buffer | stream.Stream | Promise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: string | number | boolean | Buffer | stream.Stream | Promise | T): Response; -} - -/** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - result an optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ -export interface IStrictReply extends IReplyMethods { - (err: Error, - result?: Promise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: Promise | T): Response; -} - -export interface ISessionHandler { - (request: Request, reply: IReply): void; -} - -export interface IStrictSessionHandler { - (request: Request, reply: IStrictReply): void; -} - -export interface IRequestHandler { - (request: Request): T; -} - -export interface IFailAction { - (source: string, error: any, next: () => void): void; -} -/** generates a reverse proxy handler */ -export interface IProxyHandlerConfig { - /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ - host?: string; - /** the upstream service port. */ - port?: number; - /** The protocol to use when making a request to the proxied host: - 'http' - 'https'*/ - protocol?: string; - /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ - uri?: string; - /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ - passThrough?: boolean; - /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ - localStatePassThrough?: boolean; - /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ - acceptEncoding?: boolean; - /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ - rejectUnauthorized?: boolean; - /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ - xforward?: boolean; - /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ - redirects?: boolean | number; - /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ - timeout?: number; - /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: - request - is the incoming request object. - callback - is function(err, uri, headers) where: - err - internal error condition. - uri - the absolute proxy URI. - headers - optional object where each key is an HTTP request header and the value is the header content.*/ - mapUri?(request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void): void; - /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ - onResponse?( - err: any, - res: http.ServerResponse, - req: Request, - reply: IReply, - settings: IProxyHandlerConfig, - ttl: number): void; - /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ - ttl?: number; - /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ - agent?: http.Agent; - /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ - maxSockets?: boolean | number; -} -/** TODO: fill in joi definition */ -export interface IJoi {} - -/** a validation function using the signature function(value, options, next) */ -export interface IValidationFunction { - ( - /** the object containing the path parameters. */ - value: any, - /** the server validation options. */ - options: any, - /** the callback function called when validation is completed. */ - next: (err: any, value: any) => void): void; -} -/** a custom error handler function with the signature 'function(request, reply, source, error)` */ -export interface IRouteFailFunction { - /** a custom error handler function with the signature 'function(request, reply, source, error)` */ - (/** - the [request object]. */ - request: Request, - /** the continuation reply interface. */ - reply: IReply, - /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ - source: string, - /** the error object prepared for the client response (including the validation function error under error.data). */ - error: any): void; -} - -/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ -export interface IRouteAdditionalConfigurationOptions { - /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ - app?: any; - /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. - a string with the name of an authentication strategy registered with server.auth.strategy(). - an object */ - auth?: boolean | string | - { - /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: - 'required'authentication is required. - 'optional'authentication is optional (must be valid if present). - 'try'same as 'optional' but allows for invalid authentication. */ - mode?: string; - /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ - strategies?: string | string[]; - /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: - falseno payload authentication.This is the default value. - 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. - 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ - payload?: string; - /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ - scope?: string | string[] | boolean; - /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: - anythe authentication can be on behalf of a user or application.This is the default value. - userthe authentication must be on behalf of a user. - appthe authentication must be on behalf of an application. */ - entity?: string; - /** - * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming - * request and access is granted if at least one rule matches. Each rule object must include at least one of: - */ - access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; - }; - /** an object passed back to the provided handler (via this) when called. */ - bind?: any; - /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ - cache?: { - /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: - fault'no privacy flag.This is the default setting. - 'public'mark the response as suitable for public caching. - 'private'mark the response as suitable only for private caching. */ - privacy: string; - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ - expiresIn: number; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ - expiresAt: string; - }; - /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ - cors?: { - /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ - origin?: string[]; - /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ - matchOrigin?: boolean; - /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ - isOriginExposed?: boolean; - /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ - maxAge?: number; - /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ - headers?: string[]; - /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ - additionalHeaders?: string[]; - /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ - methods?: string[]; - /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ - additionalMethods?: string[]; - /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ - exposedHeaders?: string[]; - /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ - additionalExposedHeaders?: string[]; - /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ - credentials?: boolean; - /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ - override?: boolean; - }; - /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ - files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ - relativeTo: string; - }; - - /** an alternative location for the route handler option. */ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; - /** an optional unique identifier used to look up the route using server.lookup(). */ - id?: number; - /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ - json?: { - /** the replacer function or array.Defaults to no action. */ - replacer?: Function | string[]; - /** number of spaces to indent nested object keys.Defaults to no indentation. */ - space?: number | string; - /** string suffix added after conversion to JSON string.Defaults to no suffix. */ - suffix?: string; - }; - /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ - jsonp?: string; - /** determines how the request payload is processed: */ - payload?: { - /** the type of payload representation requested. The value must be one of: - 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. - 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. - 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ - output?: string; - /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: - 'application/json' - 'application/x-www-form-urlencoded' - 'application/octet-stream' - 'text/ *' - 'multipart/form-data' */ - parse?: string | boolean; - /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ - allow?: string | string[]; - /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ - override?: string; - /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ - maxBytes?: number; - /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ - timeout?: number; - /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ - uploads?: string; - /** determines how to handle payload parsing errors. Allowed values are: - 'error'return a Bad Request (400) error response. This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action and continue processing the request. */ - failAction?: string; - }; - /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ - plugins?: IDictionary; - /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ - pre?: any[]; - /** validation rules for the outgoing response payload (response body).Can only validate object response: */ - response?: { - /** the default HTTP status code when the payload is empty. Value can be 200 or 204. - Note that a 200 status code is converted to a 204 only at the time or response transmission - (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ - emptyStatusCode?: number; - /** the default response object validation rules (for all non-error responses) expressed as one of: - true - any payload allowed (no validation performed). This is the default. - false - no payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - value - the object containing the response object. - options - the server validation options. - next(err) - the callback function called when validation is completed. */ - schema?: boolean | any; - /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ - status?: { [statusCode: number]: boolean | any }; - /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ - sample?: number; - /** defines what to do when a response fails validation.Options are: - errorreturn an Internal Server Error (500) error response.This is the default value. - loglog the error but send the response. */ - failAction?: string; - /** if true, applies the validation rule changes to the response.Defaults to false. */ - modify?: boolean; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ - security?: boolean | { - /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ - hsts?: boolean | number | { - /** the max- age portion of the header, as a number.Default is 15768000. */ - maxAge?: number; - /** a boolean specifying whether to add the includeSubdomains flag to the header. */ - includeSubdomains?: boolean; - /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ - preload?: boolean; - }; - /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ - xframe?: { - /** either 'deny', 'sameorigin', or 'allow-from' */ - rule: string; - /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ - source: string; - }; - /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ - xss?: boolean; - /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ - noOpen?: boolean; - /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ - noSniff?: boolean; - }; - /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ - state?: { - /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ - parse: boolean; - /** determines how to handle cookie parsing errors.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action. */ - failAction: string; - }; - /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ - validate?: { - /** validation rules for incoming request headers.Values allowed: - * trueany headers allowed (no validation performed).This is the default. - falseno headers allowed (this will cause all valid HTTP requests to fail). - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the request headers. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. - */ - headers?: boolean | IJoi | IValidationFunction; - - /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: - trueany path parameters allowed (no validation performed).This is the default. - falseno path variables allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the path parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - params?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: - trueany query parameters allowed (no validation performed).This is the default. - falseno query parameters allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the query parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - query?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request payload (request body).Values allowed: - trueany payload allowed (no validation performed).This is the default. - falseno payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the payload object. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - payload?: boolean | IJoi | IValidationFunction; - /** an optional object with error fields copied into every validation error response. */ - errorFields?: any; - /** determines how to handle invalid requests.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'log the error but continue processing the request. - 'ignore'take no action. - OR a custom error handler function with the signature 'function(request, reply, source, error)` where: - requestthe request object. - replythe continuation reply interface. - sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). - errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction?: string | IRouteFailFunction; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** define timeouts for processing durations: */ - timeout?: { - /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ - server: boolean | number; - /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ - socket: boolean | number; - }; - - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route description used for generating documentation (string). - */ - description?: string; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route notes used for generating documentation (string or array of strings). - */ - notes?: string | string[]; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route tags used for generating documentation (array of strings). - */ - tags?: string[]; - - /** Enable logging of routes - */ - log?: boolean; +export interface Dictionary { + [key: string]: T; } /** - * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches + * Server + * The Server object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + * [See docs](https://hapijs.com/api/16.1.1#server) + * [See docs](https://hapijs.com/api/16.1.1#server-properties) + * [See docs](https://hapijs.com/api/16.1.1#server-events) */ -export interface IRouteAdditionalConfigurationAuthAccess { - /** - * the application scope required to access the route. Value can be a scope string or an array of scope strings. - * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. - * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, - * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' - * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties - * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, - * such as 'user-{params.id}'. Defaults to false (no scope requirements). - */ - scope?: string | string[] | boolean; - /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: - * any - the authentication can be on behalf of a user or application. This is the default value. - * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. - * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. - */ - entity?: string; +export class Server extends Podium { + /** + * Creates a new Server object + */ + constructor(options?: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + * [See docs](https://hapijs.com/api/16.1.1#serverapp) + */ + app?: any; + /** + * An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + * [See docs](https://hapijs.com/api/16.1.1#serverconnections) + */ + connections: ServerConnection[]; + /** + * When the server contains exactly one connection, info is an object containing information about the sole connection + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + * [See docs](https://hapijs.com/api/16.1.1#serverinfo) + */ + info: ServerConnectionInfo | null; + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * [See docs](https://hapijs.com/api/16.1.1#serverload) + */ + load: { + /** event loop delay milliseconds. */ + eventLoopDelay: number; + /** V8 heap usage. */ + heapUsed: number; + /** RSS memory usage. */ + rss: number; + }; + /** + * When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.listener. + * [See docs](https://hapijs.com/api/16.1.1#serverlistener) + */ + listener: ServerListener | null; + /** + * An object providing access to the server methods cs://hapijs.com/api/16.1.1#servermethodname-method-options} where each server method name is an object property. + * [See docs](https://hapijs.com/api/16.1.1#servermethods) + */ + methods: Dictionary; + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + * [See docs](https://hapijs.com/api/16.1.1#servermime) + */ + readonly mime: {path(path: string): {type: string}}; + /** + * An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://hapijs.com/api/16.1.1#serverplugins) + */ + plugins: PluginsStates; + /** + * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + * [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ + readonly realm: ServerRealm; + /** + * When the server contains exactly one connection, registrations is an object where each key is a registered plugin name + * When the server contains more than one connection, each server.connections array member provides its own connection.registrations. + * TODO check and offer PR to update Hapi docs: Assuming readonly. + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ + readonly registrations: ServerRegisteredPlugins; + /** + * The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()). + * TODO, check and offer PR to update Hapi docs: Marked as optional as presumably root server does not reference itself. + * [See docs](https://hapijs.com/api/16.1.1#serverroot) + */ + root?: Server; + /** + * The server configuration object after defaults applied. + * [See docs](https://hapijs.com/api/16.1.1#serversettings) + */ + settings: ServerOptions; + /** + * The hapi module version number. + * [See docs](https://hapijs.com/api/16.1.1#serverversion) + */ + version: string; + + /** + * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) + * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) + * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) + */ + auth: ServerAuth; + + /** + * Sets a global context used as the default bind object when adding a route or an extension + * When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. + * @param context the object used to bind this in handler and extension methods. + * [See docs](https://hapijs.com/api/16.1.1#serverbindcontext) + */ + bind(context: any): void; + /** + * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) + */ + cache: ServerCacheMethod; + /** + * Adds an incoming server connection + * Returns a server object with the new connections selected. + * Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()) + * Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * + * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) for various advantage topics covering usage and caveats around use of the function in plugin register(), connectionless plugins calling connection(), etc. + * @param connection a connection configuration object or array of objects + */ + connection(options?: ServerConnectionOptions[]): Server; + connection(options?: ServerConnectionOptions): Server; + // connection: (options: ServerConnectionOptions[] | ServerConnectionOptions) => Server; + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' + * [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) + * @param encoding the decoder name string. + * @param decoder a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). + */ + decoder(encoding: string, decoder: ((options: CompressionDecoderSettings) => zlib.Gunzip)): void; + /** + * Extends various framework interfaces with custom methods + * Note that decorations apply to the entire server and all its connections regardless of current selection. + * [See docs](https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options) + * + * NOTE: it's not possible to type the result of this action. + * It's advised that in a custom definition file, you extend the ReplyNoContinue + * and ReplyWithContinue functions. See Inert `.file` for an example. + * Or if it is not part of a library / plugin then you use a namespace within + * your code to type the request, server and or reply. See + * [tests/server/decorate.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hapi/tests/server/decorate.ts) + * for examples. + * @param type the interface being decorated. Supported types: + * * 'request' - adds methods to the Request object. + * * 'reply' - adds methods to the reply interface. + * * 'server' - adds methods to the Server object. + * @param property the object decoration key name. + * @param method the extension function or other value. + * @param options if the type is 'request', supports the following optional settings: + * * apply - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + */ + decorate(type: 'request' | 'reply' | 'server', property: string, method: Function): void; + decorate(type: 'request', property: string, method: Function, options?: {apply: false}): void; + decorate(type: 'request', property: string, method: (request: Request) => Function, options: {apply: true}): void; + /** + * The server.decorate('server', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; + /** + * Used within a plugin to declare a required dependency on other plugins + * The after method is identical to setting a server extension point on 'onPreStart'. Connectionless plugins (those with attributes.connections set to false) can only depend on other connectionless plugins (server initialization will fail even of the dependency is loaded but is not connectionless). + * Dependencies can also be set via the register attributes property (does not support setting after). + * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) + * @param dependencies a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. Does not provide version dependency which should be implemented using npm peer dependencies. + * @param after an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) + */ + dependency(dependencies: string | string[], after?: AfterDependencyLoadCallback): void; + /** + * Emits a custom application event update to all the subscribed listeners + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + * [See docs](https://hapijs.com/api/16.1.1#serveremitcriteria-data-callback) + * @param criteria the event update criteria which if an object can have the following optional keys (unless noted otherwise): + * * name - the event name string (required). + * * channel - the channel name string. + * * tags - a tag string or array of tag strings. + * @param data the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param callback an optional callback method invoked when all subscribers have been notified using the signature function(). The callback is called only after all the listeners have been notified, including any event updates emitted earlier (the order of event updates are guaranteed to be in the order they were emitted). + */ + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: () => void): void; + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' + * [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) + * @param encoding the encoder name string. + * @param encoder a function using the signature function(options) where options are the encoding specific options configured in the route compression configuration option, and the return value is an object compatible with the output of node's zlib.createGzip(). + */ + encoder(encoding: string, encoder: ((options: CompressionEncoderSettings) => zlib.Gzip)): void; + /** + * Register custom application events + * [See docs](https://hapijs.com/api/16.1.1#servereventevents) + * @param events see ApplicationEvent + */ + event(events: ApplicationEvent[]): void; + event(events: ApplicationEvent): void; + /** + * Used within a plugin to expose a property via server.plugins[name] + * [See docs](https://hapijs.com/api/16.1.1#serverexposekey-value) + * @param key the key assigned (server.plugins[name][key]). + * @param value the value assigned. + */ + expose(key: string, value: any): void; + /** + * Merges an object into to the existing content of server.plugins[name] + * Note that all properties of obj are deeply cloned into server.plugins[name], so you should avoid using this method for exposing large objects that may be expensive to clone or singleton objects such as database client objects. Instead favor the server.expose(key, value) form, which only copies a reference to value. + * [See docs](https://hapijs.com/api/16.1.1#serverexposeobj) + * @param obj the object merged into the exposed properties container. + */ + expose(obj: Object): void; + /** + * Registers an extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * @param events see @ServerExtConfigurationObject + */ + ext(events: ServerExtConfigurationObject[]): void; + ext(events: ServerExtConfigurationObject): void; + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * [See docs](https://hapijs.com/api/16.1.1#serverextevent-method-options) + * @param event the extension point event name. + * @param method a function or an array of functions to be executed at a specified point during request processing. + * @param options + */ + ext(event: ServerExtPoints, method: ServerExtMethod[], options?: ServerExtOptions): void; + ext(event: ServerExtPoints, method: ServerExtMethod, options?: ServerExtOptions): void; + /** + * Registers a new handler type to be used in routes + * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + * [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) + * @param name string name for the handler being registered. Cannot override any previously registered type. + * @param method the function used to generate the route handler using the signature function(route, options) where: + * * route - the route public interface object. + * * options - the configuration object provided in the handler config. + */ + handler(name: string, method: MakeRouteHandler): void; + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection ports + * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling initialize() to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://hapijs.com/api/16.1.1#serverinitializecallback) + * @param callback the callback method when server initialization is completed or failed with the signature function(err) + */ + initialize(callback: (err: Error) => void): void; + initialize(): Promise; + /** + * When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. Utilizes the shot module for performing injections, with some additional options and response properties + * If no callback is provided, a Promise object is returned. + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + * @param options can be assigned a string with the requested URI, or an object + * @param callback the callback function with signature function(res) + */ + inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; + inject(options: string | InjectedRequestOptions, ): Promise; + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. + * [See docs](https://hapijs.com/api/16.1.1#serverlogtags-data-timestamp) + * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + */ + log(tags: string | string[], data?: string | Object | Function, timestamp?: number): void; + /** + * When the server contains exactly one connection, looks up a route configuration. + * When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method. + * [See docs](https://hapijs.com/api/16.1.1#serverlookupid) + * @param id the route identifier as set in the route options. + * @return the route public interface object if found, otherwise null. + */ + lookup(id: string): RoutePublicInterface | null; + /** + * When the server contains exactly one connection, looks up a route configuration + * When the server contains more than one connection, each server.connections array member provides its own connection.match() method. + * [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) + * @param method the HTTP method (e.g. 'GET', 'POST'). TODO check if it allows HEAD + * @param path the requested path (must begin with '/'). + * @param host optional hostname (to match against routes with vhost). + * @return the route public interface object if found, otherwise null. + */ + match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; + /** + * Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + * [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + * @param name a unique method name used to invoke the method via server.methods[name]. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get. When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject + * @param method the method function + * @param options optional configuration + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + /** + * Registers a server method function as described in server.method() using a configuration object + * [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject[]): void; + method(methods: ServerMethodConfigurationObject): void; + /** + * Subscribe a handler to an event + * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) + * @param criteria the subscription criteria which can be an event name string which can be any of the built-in server events or a custom application event registered with server.event(events). + * Or an see ServerEventCriteria. + * If 'start' - emitted when the server is started using server.start(). + * If 'stop' - emitted when the server is stopped using server.stop(). + * @param listener + */ + on(criteria: 'start' | 'stop' | string | ServerEventCriteria, listener: Function): void; + /** + * The 'log' event includes the event object and a tags object (where each tag is a key with the value true) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'log', listener: (event: ServerEventObject, tags: Podium.Tags) => void): void; + /** + * The 'request' and 'request-internal' events include the request object, the event object, and a tags object (where each tag is a key with the value true) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + * TODO submit issue to TypeScript. Using 'request' | 'request-internal' removes the type + * interference when using code like: `server.on('request', (request, event, tags) => {...}` + * Same for 'response' | 'tail'. + */ + on(criteria: 'request', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; + on(criteria: 'request-internal', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; + /** + * The 'request-error' event includes the request object and the causing error err object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'request-error', listener: (request: Request, err: Error) => void): void; + /** + * The 'response' and 'tail' events include the request object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + * See 'request' and 'request-internal' + */ + on(criteria: 'response', listener: (request: Request) => void): void; + on(criteria: 'tail', listener: (request: Request) => void): void; + /** + * The 'route' event includes the route public interface, the connection, and the server object used to add the route (e.g. the result of a plugin select operation) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'route', listener: (route: RoutePublicInterface, connection: ServerConnection, server: Server) => void): void; + /** + * Same as calling server.on() with the count option set to 1. + * TODO type this to copy the server.on specific types for 'route', 'tail', etc. + * [See docs](https://hapijs.com/api/16.1.1#serveroncecriteria-listener) + * @param criteria + * @param listener + */ + once(criteria: string | ServerEventCriteria, listener: Function): void; + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + * [See docs](https://hapijs.com/api/16.1.1#serverpathrelativeto) + * @param relativeTo the path prefix added to any relative file path starting with '.'. + */ + path(relativeTo: string): void; + /** + * Registers a plugin + * If no callback is provided, a Promise object is returned. + * Note that plugin registration are recorded on each of the available connections. When plugins express a dependency on other plugins, both have to be loaded into the same connections for the dependency requirement to be fulfilled. It is recommended that plugin registration happen after all the server connections are created via server.connection(). + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + * @param plugins + * @param options + * @param callback with signature function(err) where err an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + * A note on typings. Common use case is: + * register(Plugin, (err) => {// do more stuff}) + * so these typings save passing empty `options` object or having to + * explicity type the Error in the Callback e.g.: + * register(Plugin, {}, (err) => {// do more stuff}) or + * register(Plugin, (err: Error) => {// do more stuff}) + */ + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, callback: (err: Error | null) => void): void; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>): Promise; + register(plugins: PluginFunction | PluginRegistrationObject, callback: (err: Error | null) => void): void; + register(plugins: PluginFunction | PluginRegistrationObject): Promise; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions): Promise; + register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; + register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions): Promise; + /** + * Adds a connection route + * [See docs](https://hapijs.com/api/16.1.1#serverrouteoptions) + * @param options a route configuration object [See docs](https://hapijs.com/api/16.1.1#route-configuration) or an array of configuration objects. + */ + route(options: RouteConfiguration[]): void; + route(options: RouteConfiguration): void; + /** + * Selects a subset of the server's connections + * Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + * [See docs](https://hapijs.com/api/16.1.1#serverselectlabels) + * @param labels a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + */ + select(labels: string | string[]): Server; + /** + * Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false) + * If no callback is provided, a Promise object is returned. + * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling start() to abort the process when the server fails to start properly. If you must try to resume after a start error, call server.stop() first to reset the server state. + * If a started server is started again, the second call to start() will only start new connections added after the initial start() was called. No events will be emitted and no extension points invoked. + * [See docs](https://hapijs.com/api/16.1.1#serverstartcallback) + * @param callback the callback method when server startup is completed or failed with the signature function(err) where: + * * err - any startup error condition. + */ + start(callback: (err?: Error) => void): void; + start(): Promise; + /** + * HTTP state management [See docs](https://tools.ietf.org/html/rfc6265) uses client cookies to persist a state across multiple requests. Registers a cookie definitions + * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) + * @param name the cookie name string. + * @param options optional cookie settings + */ + state(name: string, options?: ServerStateCookieConfiguationObject): void; + /** + * Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout) + * If no callback is provided, a Promise object is returned. + * [See docs](https://hapijs.com/api/16.1.1#serverstopoptions-callback) + * @param options options object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @param callback optional callback method which is called once all the connections have ended and it is safe to exit the process with signature function(err) where: + * * err - any termination error condition. + */ + stop(options: {timeout: number} | null, callback: (err?: Error) => void): void; + stop(options?: {timeout: number}): Promise; + /** + * Returns a copy of the routing table + * Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + * When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) + * @param host optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + */ + table(host?: string): RoutingTableEntry[]; } -/** server.realm http://hapijs.com/api#serverrealm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), - the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). - Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { -console.log(server.realm.modifiers.route.prefix); -return next(); -}; +/** + * Server Options + * Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) */ -export interface IServerRealm { - /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ - modifiers: { - /** routes preferences: */ - route: { - /** - the route path prefix used by any calls to server.route() from the server. */ - prefix: string; - /** the route virtual host settings used by any calls to server.route() from the server. */ - vhost: string; - }; - }; - /** the active plugin name (empty string if at the server root). */ - plugin: string; - /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ - plugins: IDictionary; - /** settings overrides */ - settings: { - files: { - relativeTo: any; - }; - bind: any; - }; -} -/** server.state(name, [options]) http://hapijs.com/api#serverstatename-options - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ -export interface IServerState { - /** - the cookie name string. */name: string; - - /** - are the optional cookie settings: */options: { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; - /** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean - /** - the path scope.Defaults to null (no path).*/path: any; - /** - the domain scope.Defaults to null (no domain). */domain: any; - /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue(request: Request, next: (err: any, value: any) => void): void; - /** - encoding performs on the provided value before serialization. Options are: - 'none' - no encoding. When used, the cookie value must be a string. This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON-stringified than encoded using Base64. - 'form' - object value is encoded using the x-www-form-urlencoded method. - 'iron' - Encrypts and sign the value using iron.*/ - encoding: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { - /** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; - /** - password used for HMAC key generation.*/password: string; - }; - /** - password used for 'iron' encoding.*/password: string; - /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; - /** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; - /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; - /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; - /** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; - }; +export interface ServerOptions { + /** app - application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** + * cache - sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + * * a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. + * * a CatboxServerOptionsCacheConfiguration configuration object + * * an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. + */ + cache?: Catbox.EnginePrototype | CatboxServerOptionsCacheConfiguration | CatboxServerOptionsCacheConfiguration[]; + /** sets the default connections configuration which can be overridden by each connection */ + connections?: ConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object with: */ + debug?: false | { + /** a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log?: string[] | false; + /** a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + request?: string[] | false; + }; + /** process load monitoring */ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling). */ + sampleInterval?: number; + }; + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime. */ + mime?: MimosOptions; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}. */ + plugins?: Object; + /** if false, will not use node domains to protect against exceptions thrown in handlers and other external code. Defaults to true. */ + useDomains?: boolean; } -export interface IFileHandlerConfig { - /** a path string or function as described above.*/ - path: string; - /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ - lookupCompressed: boolean; +/** + * The server event object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ +export interface ServerEventObject { + /** the event timestamp. */ + timestamp: number; + /** if the event relates to a request, the request id. */ + request: string; + /** if the event relates to a server, the server.info.uri. */ + server: string; + /** an array of tags (e.g. ['error', 'http']). */ + tags: string[]; + /** optional event-specific information. */ + data: any; + /** true if the event was generated internally by the framework. */ + internal: boolean; } -/**http://hapijs.com/api#route-handler - Built-in handlers - - The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ -export interface IRouteHandlerConfig { - /** generates a static file endpoint for serving a single file. file can be set to: - a relative or absolute file path string (relative paths are resolved based on the route files configuration). - a function with the signature function(request) which returns the relative or absolute file path. - an object with the following options */ - file?: string | IRequestHandler | IFileHandlerConfig; - /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: - path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: - a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. - an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). - a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. - index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. - listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. - showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. - redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. - lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. - defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ - directory?: { - path: string | string[] | IRequestHandler | IRequestHandler; - index?: boolean | string | string[]; - listing?: boolean; - showHidden?: boolean; - redirectToSlash?: boolean; - lookupCompressed?: boolean; - defaultExtension?: string; - }; - proxy?: IProxyHandlerConfig; - view?: string | { - template: string; - context: { - payload: any; - params: any; - query: any; - pre: any; - } - }; - config?: { - handler: any; - bind: any; - app: any; - plugins: { - [name: string]: any; - }; - pre: Array<() => void>; - validate: { - headers: any; - params: any; - query: any; - payload: any; - errorFields?: any; - failAction?: string | IFailAction; - }; - payload: { - output: { - data: any; - stream: any; - file: any; - }; - parse?: any; - allow?: string | string[]; - override?: string; - maxBytes?: number; - uploads?: number; - failAction?: string; - }; - response: { - schema: any; - sample: number; - failAction: string; - }; - cache: { - privacy: string; - expiresIn: number; - expiresAt: number; - }; - auth: string | boolean | { - mode: string; - strategies: string[]; - payload?: boolean | string; - tos?: boolean | string; - scope?: string | string[]; - entity: string; - }; - cors?: boolean; - jsonp?: string; - description?: string; - notes?: string | string[]; - tags?: string[]; - }; -} -/** Route configuration - The route configuration object*/ -export interface IRouteConfiguration { - /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ - path: string; - /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). - * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ - method: string | string[]; - /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ - vhost?: string; - /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; - /** - additional route options.*/ - config?: IRouteAdditionalConfigurationOptions; -} -/** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ -export interface IRoute { - /** the route HTTP method. */ - method: string; - /** the route path. */ - path: string; - /** the route vhost option if configured. */ - vhost?: string | string[]; - /** the [active realm] associated with the route.*/ - realm: IServerRealm; - /** the [route options] object with all defaults applied. */ - settings: IRouteAdditionalConfigurationOptions; +/** + * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) + */ +export interface ServerEventCriteria { + /** the event name string (required). */ + name: string; + /** if true, the listener method receives an additional callback argument which must be called when the method completes. No other event will be emitted until the callback methods is called. The method signature is function(). If block is set to a positive integer, the value is used to set a timeout after which any pending events will be emitted, ignoring the eventual call to callback. Defaults to false (non blocking). */ + block?: boolean; + /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ + channels?: string | string[]; + /** if true, the data object passed to server.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.once(). Defaults to no limit. */ + count?: number; + /** + * the event tags (if present) to subscribe to + * If the object is given: + * * tags - a tag string or array of tag strings. + * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** if true, and the data object passed to server.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ + spread?: boolean; + /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). Defaults to the event registration option (which defaults to false). */ + tags?: boolean; } -export interface IServerAuthScheme { - /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: - request - the request object. - reply - the reply interface the authentication method must call when done authenticating the request where: - reply(err, response, result) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - result - an object containing: - credentials - the authenticated credentials. - artifacts - optional authentication artifacts. - reply.continue(result) - is called if authentication succeeded where: - result - same object as result above. - When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. - .If the err returned by the reply() method includes a message, no additional strategies will be attempted. - If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var scheme = function (server, options) { - return { - authenticate: function (request, reply) { - var req = request.raw.req; - var authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply(null, { credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme);*/ - authenticate(request: Request, reply: IReply): void; - authenticate(request: Request, reply: IStrictReply): void; - /** payload(request, reply) - optional function called to authenticate the request payload where: - request - the request object. - reply(err, response) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - reply.continue() - is called if payload authentication succeeded. - When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ - payload?(request: Request, reply: IReply): void; - payload?(request: Request, reply: IStrictReply): void; - /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: - request - the request object. - reply(err, response) - is called if an error occurred where: - err - any authentication error. - response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. - reply.continue() - is called if the operation succeeded.*/ - response?(request: Request, reply: IReply): void; - response?(request: Request, reply: IStrictReply): void; - /** an optional object */ - options?: { - /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ - payload: boolean; - }; +/** + * Server methods, user configured + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethods) + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + */ +export interface ServerMethod { + /** Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 */ + (...args: (any | ServerMethodNext)[]): void; + /** the method must return a value (result, Error, or a promise) or throw an Error. */ + (...args: any[]): any | Error | Promise; + /** When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject */ + cache?: ServerMethodNameCacheObject; } -/**the response object where: - statusCode - the HTTP status code. - headers - an object containing the headers set. - payload - the response payload string. - rawPayload - the raw response payload buffer. - raw - an object with the injection request and response objects: - req - the simulated node request object. - res - the simulated node response object. - result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - request - the request object.*/ -export interface IServerInjectResponse { - statusCode: number; - headers: IDictionary; - payload: string; - rawPayload: Buffer; - raw: { - req: http.IncomingMessage; - res: http.ServerResponse - }; - result: string; - request: Request; +/** + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + * @param err error response if the method failed. + * @param result the return value. + * @param ttl 0 if result is valid but cannot be cached. Defaults to cache policy. + */ +export interface ServerMethodNext { + (err: Error | null, result: any, ttl?: number): void; } -export interface IServerInject { - (options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void; - (options: string | IServerInjectOptions): Promise; +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ +export interface ServerMethodNameCacheObject { + /** + * function that can be used to clear the cache for a given key. + * @param ...args any number of string, number or boolean. If other types then generateKey function must be specified. + * @param callback last argument is a callback. + * Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 + */ + drop(...args: (any | Function)[]): void; + /** an object with cache statistics, see stats documentation for catbox. */ + stats: Catbox.CacheStatisticsObject; } -export interface IServerInjectOptions { - /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ - method: string; - /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ - url: string; - /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ - headers?: IDictionary; - /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ - payload?: string | {} | Buffer; - /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ - credentials?: any; - /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ - artifacts?: any; - /** sets the initial value of request.app*/ - app?: any; - /** sets the initial value of request.plugins*/ - plugins?: any; - /** allows access to routes with config.isInternal set to true. Defaults to false.*/ - allowInternals?: boolean; - /** sets the remote address for the incoming connection.*/ - remoteAddress?: boolean; - /**object with options used to simulate client request stream conditions for testing: - error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. - close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. - end - if false, does not end the stream. Defaults to true.*/ - simulate?: { - error: boolean; - close: boolean; - end: boolean; - }; +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ +export interface ServerMethodOptions { + /** a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. */ + bind?: any; + /** the same cache configuration used in server.cache(). The generateTimeout option is required. */ + cache?: CatboxServerCacheConfiguration; + /** + * if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + * TODO: understand and type "an additional argument with the signature function(err, result, cached, report)" if appropriate. + */ + callback?: boolean; + /** a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). */ + generateKey?(args: any[]): string | null; } -/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path.*/ -export interface IConnectionTable { - info: any; - labels: any; - table: IRoute[]; +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) */ +export interface ServerMethodConfigurationObject { + name: string; + method: ServerMethod; + options: ServerMethodOptions; } -export interface ICookieSettings { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ - ttl?: number; - /** - sets the 'Secure' flag.Defaults to false.*/ - isSecure?: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/ - isHttpOnly?: boolean; - /** - the path scope.Defaults to null (no path).*/ - path?: string; - /** - the domain scope.Defaults to null (no domain).*/ - domain?: any; - /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue?(request: Request, next: (err: any, value: any) => void): void; - /** - encoding performs on the provided value before serialization.Options are: - 'none' - no encoding.When used, the cookie value must be a string.This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON- stringified than encoded using Base64. - 'form' - object value is encoded using the x- www - form - urlencoded method. */ - encoding?: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: - integrity - algorithm options.Defaults to require('iron').defaults.integrity. - password - password used for HMAC key generation. */ - sign?: { integrity: any; password: string; }; - password?: string; - iron?: any; - ignoreErrors?: boolean; - clearInvalid?: boolean; - strictHeader?: boolean; - passThrough?: any; +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Caching with Catbox + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * TODO confirm this is the same as CatboxServerCacheConfiguration + * + * ** + * Server instantiation options configuration for Catbox cache + * TODO: check it extends Catbox.PolicyOptions and this is what "other options passed to the catbox strategy used." means. + * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > cache > a configuration object + * ** + * export interface CatboxServerOptionsCacheConfiguration extends Catbox.IPolicyOptions { + * // a prototype function or catbox engine object. + * engine: Catbox.EnginePrototypeOrObject; + * // an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * name?: string; + * // if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * shared?: boolean; + * } + */ +export type CatboxServerOptionsCacheConfiguration = CatboxServerCacheConfiguration; + +/** + * Server cache method configuration for Catbox cache + * Used for "Provisions a cache segment within the server cache facility" + * For context [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + * Also used in [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) > options.cache + */ +export interface CatboxServerCacheConfiguration extends Catbox.PolicyOptions { + /** the cache name configured in server.cache. Defaults to the default cache. */ + cache?: string; + /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ + segment?: string; + /** if true, allows multiple cache provisions to share the same segment. Default to false. */ + shared?: boolean; + /** + * a prototype function or catbox engine object. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `engine` option. But server.cache.provision of `options` says "same as the server cache configuration options.". + * TODO confirm once PR to hapi docs accepted / rejected. + */ + engine?: Catbox.EnginePrototypeOrObject; + /** + * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `name` option. But server.cache.provision of `options` says "same as the server cache configuration options.". + */ + name?: string; } -/** method - the method function with the signature is one of: - function(arg1, arg2, ..., argn, next) where: - arg1, arg2, etc. - the method function arguments. - next - the function called when the method is done with the signature function(err, result, ttl) where: - err - error response if the method failed. - result - the return value. - ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. - function(arg1, arg2, ..., argn) where: - arg1, arg2, etc. - the method function arguments. - the callback option is set to false. - the method must returns a value (result, Error, or a promise) or throw an Error.*/ -export interface IServerMethod { - // (): void; - // (next: (err: any, result: any, ttl: number) => void): void; - // (arg1: any): void; - // (arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; - // (arg1: any, arg2: any): void; - (...args: any[]): void; +/** + * Additional notes + * payload - In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + */ +export interface InjectedRequestOptions extends Shot.RequestOptions { + /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. */ + credentials?: any; + /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. */ + artifacts?: any; + /** sets the initial value of request.app. */ + app?: any; + /** sets the initial value of request.plugins. */ + plugins?: PluginsStates; + /** allows access to routes with config.isInternal set to true. Defaults to false. */ + allowInternals?: boolean; } -/** options - optional configuration: - bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. - cache - the same cache configuration used in server.cache(). - callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. - generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ -export interface IServerMethodOptions { - bind?: any; - cache?: ICatBoxCachePolicyOptions; - callback?: boolean; - generateKey?(args: any[]): string; + +/** + * the response object from server.inject + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + */ +export interface InjectedResponseObject extends Shot.ResponseObject { + /** the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). */ + result: Shot.ResponseObject | string; + /** the request object. */ + request: InjectedRequestOptions; } -/** Request object - The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. - Request events +/** + * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > connections + */ +export interface ConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** if false, response content encoding is disabled. Defaults to true */ + compression?: boolean; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive?: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash?: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: RouteAdditionalConfigurationOptions; + /** sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the [state configuration object](https://hapijs.com/api/16.1.1#serverstatename-options). */ + state?: ServerStateCookieConfiguationObject; +} - The request object supports the following events: +/** + * a connection configuration object or array of objects with the following optional keys. + * Any connections configuration server defaults can be included to override and customize the individual connection. + * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) + */ +export interface ServerConnectionOptions extends ConnectionConfigurationServerDefaults { + /** host - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'. */ + host?: string; + /** address - sets the host name or IP address the connection will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0'). Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine. */ + address?: string; + /** port - the TCP port the connection will listen to. Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port). If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe. */ + port?: string | number; + /** uri - the full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the connection info.uri otherwise constructed from the connection settings. */ + uri?: string; + /** listener - optional node.js HTTP (or HTTPS) http.Server object or any compatible object. If the listener needs to be manually started, set autoListen to false. If the listener uses TLS, set tls to true. */ + listener?: http.Server; + /** autoListen - indicates that the connection.listener will be started manually outside the framework. Cannot be specified with a port setting. Defaults to true. */ + autoListen?: boolean; + /** labels - a string or string array of labels used to server.select() specific connections matching the specified labels. Defaults to an empty array [] (no labels). */ + labels?: string | string[]; + /** tls - used to create an HTTPS connection. The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS [documentation](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener}) . Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: true | https.RequestOptions; +} - 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the request payload finished reading. The event method signature is function (). - 'disconnect' - emitted when a request errors or aborts unexpectedly. - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); +/** + * For context see RouteAdditionalConfigurationOptions > compression + * For context [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) + */ +export type CompressionEncoderSettings = any; - server.ext('onRequest', function (request, reply) { +/** + * For context see RouteAdditionalConfigurationOptions > payload > compression + * For context [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) + */ +export type CompressionDecoderSettings = any; -var hash = Crypto.createHash('sha1'); -request.on('peek', function (chunk) { +/** + * an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) + * Also see Server.dependency + * @param server the server the dependency() method was called on. + * @param next the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + * * err - internal error condition, which is returned back via the server.initialize() or server.start() callback. + */ +export interface AfterDependencyLoadCallback { + (server: Server, next: (err?: Error) => void): void; +} -hash.update(chunk); +/** For context see RouteAdditionalConfigurationOptions > auth */ +export interface AuthOptions { + /** + * the authentication mode. Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional (must be valid if present). + * * 'try' - same as 'optional' but allows for invalid authentication. + */ + mode?: 'required' | 'optional' | 'try'; + /** a string array of strategy names in order they should be attempted. If only one strategy is used, strategy can be used instead with the single string value. Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies?: string[]; + strategy?: string; + /** + * if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the options.payload to true. Available values: + * * false - no payload authentication. This is the default value. + * * 'required' - payload authentication required. This is the default value when the scheme sets options.payload to true. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + */ + payload?: false | 'required' | 'optional'; + /** specifying the route access rules. */ + access?: RouteAuthAccessConfiguationObject | RouteAuthAccessConfiguationObject[]; + /** (undocumented) Convenience way of setting access.scope, will over write all values in `access` */ + scope?: false | string | string[]; + /** (undocumented) Convenience way of setting access.entity, will over write all values in `access` */ + entity?: 'any' | 'user' | 'app'; +} + +/** + * Each rule is evaluated against an incoming request and access is granted if at least one rule matches. Each rule object must include at least one of: + * For context see RouteAdditionalConfigurationOptions > auth > an object > access + */ +export interface RouteAuthAccessConfiguationObject { + /** the application scope required to access the route. Value can be a scope string or an array of scope strings. The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access properties on the request object (query and params) to populate a dynamic scope by using {} characters around the property name, such as 'user-{params.id}'. Defaults to false (no scope requirements). */ + scope?: false | string | string[]; + /** + * the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: + * * any - the authentication can be on behalf of a user or application. This is the default value. + * * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. + * * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + */ + entity?: 'any' | 'user' | 'app'; +} + +/** + * For context see RouteAdditionalConfigurationOptions > cache + */ +export type RouteCacheOptions = { + /** + * determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * 'default' - no privacy flag. This is the default setting. + * * 'public' - mark the response as suitable for public caching. + * * 'private' - mark the response as suitable only for private caching. + */ + privacy?: 'default' | 'public' | 'private'; + /** an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive. Defaults to [200]. */ + statuses?: number[]; + /** a string with the value of the 'Cache-Control' header when caching is disabled. Defaults to 'no-cache'. */ + otherwise?: string; +} & ({ + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: undefined; +} | { + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: undefined; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: string; +} | { + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: undefined; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: undefined; }); -request.once('finish', function () { - -console.log(hash.digest('hex')); -}); - -request.once('disconnect', function () { - -console.error('request aborted'); -}); - -return reply.continue(); -});*/ -export class Request extends Events.EventEmitter { - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** authentication information*/ - auth: { - /** true is the request has been successfully authenticated, otherwise false.*/ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ - credentials: any; - /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ - artifacts: any; - /** the route authentication mode.*/ - mode: any; - /** the authentication error is failed and mode set to 'try'.*/ - error: any; - }; - /** the connection used by this request*/ - connection: ServerConnection; - /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ - domain: any; - /** the raw request headers (references request.raw.headers).*/ - headers: IDictionary; - /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ - id: string; - /** request information */ - info: { - /** the request preferred encoding. */ - acceptEncoding: string; - /** if CORS is enabled for the route, contains the following: */ - cors: { - isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ - }; - /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ - host: string; - /** the hostname part of the 'Host' header (e.g. 'example.com').*/ - hostname: string; - /** request reception timestamp. */ - received: number; - /** content of the HTTP 'Referrer' (or 'Referer') header. */ - referrer: string; - /** remote client IP address. */ - remoteAddress: string; - /** remote client port. */ - remotePort: number; - /** request response timestamp (0 is not responded yet). */ - responded: number; - }; - /** the request method in lower case (e.g. 'get', 'post'). */ - method: string; - /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ - mime: string; - /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ - orig: { - params: any; - query: any; - payload: any; - }; - /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ - params: IDictionary; - /** an array containing all the path params values in the order they appeared in the path.*/ - paramsArray: string[]; - /** the request URI's path component. */ - path: string; - /** the request payload based on the route payload.output and payload.parse settings.*/ - payload: stream.Readable | Buffer | any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ - plugins: any; - /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ - pre: IDictionary; - /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ - response: Response; - /**preResponses - same as pre but represented as the response object created by the pre method.*/ - preResponses: any; - /**an object containing the query parameters.*/ - query: any; - /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ - raw: { - req: http.IncomingMessage; - res: http.ServerResponse; - }; - /** the route public interface.*/ - route: IRoute; - /** the server object. */ - server: Server; - /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - state: any; - /** complex object contining details on the url */ - url: { - /** null when i tested */ - auth: any; - /** null when i tested */ - hash: any; - /** null when i tested */ - host: any; - /** null when i tested */ - hostname: any; - href: string; - path: string; - /** path without search*/ - pathname: string; - /** null when i tested */ - port: any; - /** null when i tested */ - protocol: any; - /** querystring parameters*/ - query: IDictionary; - /** querystring parameters as a string*/ - search: string; - /** null when i tested */ - slashes: any; - }; - - /** request.setUrl(url) - - Available only in 'onRequest' extension methods. - - Changes the request URI before the router begins processing the request where: - - url - the new request path value. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - });*/ - setUrl(url: string | url.Url): void; - /** request.setMethod(method) - - Available only in 'onRequest' extension methods. - - Changes the request method before the router begins processing the request where: - - method - is the request HTTP method (e.g. 'GET'). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to 'GET' - request.setMethod('GET'); - return reply.continue(); - });*/ - setMethod(method: string): void; - - /** request.log(tags, [data, [timestamp]]) - - Always available. - - Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.on('request', function (request, event, tags) { - - if (tags.error) { - console.log(event); - } - }); - - var handler = function (request, reply) { - - request.log(['test', 'error'], 'Test event'); - return reply(); - }; - */ - log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ - tags: string | string[], - /** an optional message string or object with the application data being logged.*/ - data?: any, - /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ - timestamp?: number): void; - - /** request.getLog([tags], [internal]) - - Always available. - - Returns an array containing the events matching any of the tags specified (logical OR) - request.getLog(); - request.getLog('error'); - request.getLog(['error', 'auth']); - request.getLog(['error'], true); - request.getLog(false);*/ - - getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ - tags?: string, - /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ - internal?: boolean): string[]; - - /** request.tail([name]) - - Available until immediately after the 'response' event is emitted. - - Adds a request tail which has to complete before the request lifecycle is complete where: - - name - an optional tail name used for logging purposes. - Returns a tail function which must be called when the tail activity is completed. - - Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - - When all tails completed, the server emits a 'tail' event. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - var get = function (request, reply) { - - var dbTail = request.tail('write to database'); - - db.save('key', 'value', function () { - - dbTail(); - }); - - return reply('Success!'); - }; - - server.route({ method: 'GET', path: '/', handler: get }); - - server.on('tail', function (request) { - - console.log('Request completed including db activity'); - });*/ - tail(/** an optional tail name used for logging purposes.*/ - name?: string): Function; -} -/** Response events - - The response object supports the following events: - - 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onPreResponse', function (request, reply) { - -var response = request.response; -if (response.isBoom) { -return reply(); +/** + * For context see RouteAdditionalConfigurationOptions > cors + */ +export interface CorsConfigurationObject { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. Defaults to any origin ['*']. */ + origin?: string[] | '*'; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'] */ + headers?: string[]; + /** a strings array of additional headers to headers. Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. */ + credentials?: boolean; } -var hash = Crypto.createHash('sha1'); -response.on('peek', function (chunk) { - -hash.update(chunk); -}); - -response.once('finish', function () { - -console.log(hash.digest('hex')); -}); - -return reply.continue(); -});*/ -export class Response extends Events.EventEmitter { - isBoom: boolean; - /** the HTTP response status code. Defaults to 200 (except for errors).*/ - statusCode: number; - /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ - headers: IDictionary; - /** the value provided using the reply interface.*/ - source: any; - /** a string indicating the type of source with available values: - 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). - 'buffer' - a Buffer. - 'view' - a view generated with reply.view(). - 'file' - a file generated with reply.file() of via the directory handler. - 'stream' - a Stream. - 'promise' - a Promise object. */ - variety: string; - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ - plugins: any; - /** settings - response handling flags: - charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. - encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. - passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. - stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. - ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. - varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ - settings: { - charset: string; - encoding: string; - passThrough: boolean; - stringify: any; - ttl: number; - varyEtag: boolean; - }; - - /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: - length - the header value. Must match the actual payload size.*/ - bytes(length: number): Response; - - /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ - charset(charset: string): Response; - - /** sets the HTTP status code where: - statusCode - the HTTP status code.*/ - code(statusCode: number): Response; - - /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ - created(uri: string): Response; - - /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ - encoding(encoding: string): Response; - - /** etag(tag, options) - sets the representation entity tag where: - tag - the entity tag string without the double-quote. - options - optional settings where: - weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. - vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ - etag(tag: string, options: { - weak: boolean; vary: boolean; - }): Response; - - /**header(name, value, options) - sets an HTTP header where: - name - the header name. - value - the header value. - options - optional settings where: - append - if true, the value is appended to any existing header value using separator. Defaults to false. - separator - string used as separator when appending to an exiting value. Defaults to ','. - override - if false, the header value is not set if an existing value present. Defaults to true.*/ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */ - hold(): Response; - - /** location(uri) - sets the HTTP 'Location' header where: - uri - an absolute or relative URI used as the 'Location' header value.*/ - location(uri: string): Response; - - /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: - uri - an absolute or relative URI used to redirect the client to another resource. */ - redirect(uri: string): Response; - - /** replacer(method) - sets the JSON.stringify() replacer argument where: - method - the replacer function or array. Defaults to none.*/ - replacer(method: Function | Function[]): Response; - - /** spaces(count) - sets the JSON.stringify() space argument where: - count - the number of spaces to indent nested object keys. Defaults to no indentation. */ - spaces(count: number): Response; - - /**state(name, value, [options]) - sets an HTTP cookie where: - name - the cookie name. - value - the cookie value. If no encoding is defined, must be a string. - options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - state(name: string, value: string, options?: any): Response; - - /** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */ - send(): void; - - /** sets a string suffix when the response is process via JSON.stringify().*/ - suffix(suffix: string): void; - - /** overrides the default route cache expiration rule for this response instance where: - msec - the time-to-live value in milliseconds.*/ - ttl(msec: number): void; - - /** type(mimeType) - sets the HTTP 'Content-Type' header where: - mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ - type(mimeType: string): Response; - - /** clears the HTTP cookie by setting an expired value where: - name - the cookie name. - options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - unstate(name: string, options?: { [key: string]: string }): Response; - - /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: - header - the HTTP request header name.*/ - vary(header: string): void; +/** + * An object describing the extension function used whilst registering the extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see RouteAdditionalConfigurationOptions > ext + */ +export interface ServerExtConfigurationObject { + /** the extension point event name. */ + type: ServerExtPoints; + /** + * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler + */ + method: ServerExtMethod | ServerExtMethod[]; + options?: ServerExtOptions; } -/** When using the redirect() method, the response object provides these additional methods */ -export class ResponseRedirect extends Response { - /** sets the status code to 302 or 307 (based on the rewritable() setting) where: - isTemporary - if false, sets status to permanent. Defaults to true.*/ - temporary(isTemporary: boolean): void; - /** sets the status code to 301 or 308 (based on the rewritable() setting) where: - isPermanent - if true, sets status to temporary. Defaults to false. */ - permanent(isPermanent: boolean): void; +/** + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > method + */ +export type ServerExtMethod = ServerExtFunction | ServerExtRequestHandler; - /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: - isRewritable - if false, sets to non-rewritable. Defaults to true. - Permanent Temporary - Rewritable 301 302(1) - Non-rewritable 308(2) 307 - Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ - rewritable(isRewritable: boolean): void; +/** + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > options + */ +export interface ServerExtOptions { + /** before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. */ + before: string | string[]; + /** after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. */ + after: string | string[]; + /** bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. */ + bind: any; + /** sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'connection' which applies to any route added to the connection the extension is added to. */ + sandbox?: 'connection' | 'plugin'; } -/** info about a server connection */ -export interface IServerConnectionInfo { - /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ - id: string; - /** - the connection creation timestamp.*/ - created: number; - /** - the connection start timestamp (0 when stopped).*/ - started: number; - /** the connection port based on the following rules: - the configured port value before the server has been started. - the actual port assigned when no port is configured or set to 0 after the server has been started.*/ - port: number; - /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ - host: string; - /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ - address: string; - /** - the protocol used: - 'http' - HTTP. - 'https' - HTTPS. - 'socket' - UNIX domain socket or Windows named pipe.*/ - protocol: string; - /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ - uri: string; +/** + * [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) + * The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > type + */ +export type ServerExtPoints = 'onRequest' | 'onPreResponse' | 'onPreAuth' | 'onPostAuth' | 'onPreHandler' | 'onPostHandler' | 'onPreResponse' | 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; + +/** + * Server extension function registered an one of the server extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see ServerExtConfigurationObject + * @param server - the server object. + * @param next - the continuation method with signature function(err). + * @param this - the object provided via options.bind or the current active context set with server.bind(). + */ +export interface ServerExtFunction { + (server: Server, next: ContinuationFunction): void; +} + +/** + * For context see RouteAdditionalConfigurationOptions > payload + */ +export interface RoutePayloadConfigurationObject { + /** + * the type of payload representation requested. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, the raw Buffer is returned. This is the default value except when a proxy handler is used. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + * * 'file' - the incoming payload is written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleanup. + */ + output?: PayLoadOutputOption; + /** + * can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + * * 'application/json' + * * 'application/x-www-form-urlencoded' + * * 'application/octet-stream' + * * 'text/*' + * * 'multipart/form-data' + */ + parse?: 'gunzip' | boolean; + /** + * overrides payload processing for multipart requests. Value can be one of: + * * false - disables multipart processing. + * * object with the following required options: + * * output - same as the payload.output option with an additional value option: + * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * headers - the part headers. + * * filename - the part file name. + * * payload - the processed part payload. + */ + multipart?: false | { + output: PayLoadOutputOption | 'annotated'; + }; + /** a string or an array of strings with the allowed mime types for the endpoint. Defaults to any of the supported mime types listed above. Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received. Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. Set to false to disable. Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads. Defaults to os.tmpdir(). */ + uploads?: string; + /** + * determines how to handle payload parsing errors. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + */ + failAction?: 'error' | 'log' | 'ignore'; + /** the default 'Content-Type' HTTP header value is not present. Defaults to 'application/json'. */ + defaultContentType?: string; + /** an object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in the root option compression. */ + compression: Dictionary; +} + +export type PayLoadOutputOption = 'data' | 'stream' | 'file'; + +/** + * events must be one of: + * * an event name string. + * * an event options object see ApplicationEventOptionsObject + * * a podium [See docs](https://github.com/hapijs/podium) emitter object. + * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter + */ +export type ApplicationEvent = string | ApplicationEventOptionsObject | Podium; + +/** + * an event options object + * For context see ApplicationEvent + * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter + */ +export interface ApplicationEventOptionsObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** if true, the data object passed to server.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ + clone?: boolean; + /** if true, the data object passed to server.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ + spread?: boolean; + /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). A configuration override can be set by each listener. Defaults to false. */ + tags?: boolean; + /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ + shared?: boolean; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Route + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Route configuration + * The route configuration object + * + * [See docs](https://hapijs.com/api/16.1.1#route-configuration) + * + * TODO typings check that the following refers to RouteAdditionalConfigurationOptions "Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on." + */ +export interface RouteConfiguration { + /** the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. */ + path: string; + /** the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. */ + method: HTTP_METHODS_PARTIAL | '*' | (HTTP_METHODS_PARTIAL | '*')[]; + /** an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. */ + vhost?: string; + /** the function called to generate the response after successful authentication and validation. The handler function is described in Route handler. If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed. Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler. */ + handler?: string | RouteHandler | RouteHandlerPlugins; + /** additional route options. The config value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. */ + config?: RouteAdditionalConfigurationOptions | ((server: Server) => RouteAdditionalConfigurationOptions); +} + +/** + * Route options + * Each route can be customize to change the default behavior of the request lifecycle using the following options: + * [See docs](https://hapijs.com/api/16.1.1#route-options) + */ +export interface RouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** + * Authentication configuration. Value can be: + * * false to disable authentication if a default strategy is set. + * * a string with the name of an authentication strategy registered with server.auth.strategy(). + * * an object + */ + auth?: false | string | AuthOptions; + /** an object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. */ + bind?: any; + /** + * Route cache options + * if the route method is 'GET', the route can be configured to include caching directives in the response. The default Cache-Control: no-cache header can be disabled by setting cache to false. Caching can be customized using an object + * TODO check: the default is to have 'Cache-Control: no-cache', but on first reading is a contridiction as you can disabled cache and disabled no-cache by setting RouteCacheOptions to false? + */ + cache?: boolean | RouteCacheOptions; + /** an object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in payload.compression. */ + compression?: Dictionary; + /** the Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. CORS headers are disabled by default (false). To enable, set cors to true, or to an object */ + cors?: boolean | CorsConfigurationObject; + /** defined a route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the [server.ext(events)](https://hapijs.com/api/16.1.1#serverextevents) event argument. */ + ext?: Dictionary; + /** defines the behavior for accessing files: */ + files?: { + /** determines the folder relative paths are resolved against. */ + relativeTo: string; + }; + /** an alternative location for the route.handler option. */ + handler?: string | RouteHandler; + /** an optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes with an array of methods. */ + id?: string; + /** if true, the route cannot be accessed through the HTTP connection but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. Defaults to false. */ + isInternal?: boolean; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload. Supports the following: */ + json?: Json.StringifyArguments & { + /** string suffix added after conversion to JSON string. Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Does not work with stream responses. Headers content-type and x-content-type-options are set to text/javascript and nosniff respectively, and will override those headers even if explicitly set by response.type() */ + jsonp?: string; + /** if true, request level logging is enabled (accessible via request.getLog()). */ + log?: boolean; + /** + * determines how the request payload is processed + * [See docs](https://hapijs.com/api/16.1.1#route-options) + */ + payload?: RoutePayloadConfigurationObject; + /** plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: Object; + /** an array with [route prerequisites](https://hapijs.com/api/16.1.1#route-prerequisites) methods which are executed in serial or in parallel before the handler is called. */ + pre?: RoutePrerequisitesArray; + /** processing rules for the outgoing response */ + response?: RouteResponseConfigurationObject; + /** sets common security headers (disabled by default). To enable set security to true or to an object with the following options: See RouteSecurityConfigurationObject */ + security?: boolean | RouteSecurityConfigurationObject; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object. Defaults to true. */ + parse?: boolean; + /** + * determines how to handle cookie parsing errors. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action. + */ + failAction: 'error' | 'log' | 'ignore'; + }; + /** request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: */ + validate?: RouteValidationConfigurationObject; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response. Disabled by default (false). */ + server?: boolean | number; + /** by default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Defaults to undefined which leaves the node default unchanged. Set to false to disable socket timeouts. */ + socket?: boolean | number; + }; + + /** + * TODO decide on moving these to an extended interface of RouteAdditionalConfigurationOptions + */ + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route description used for generating documentation + */ + description?: string; + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route notes used for generating documentation + */ + notes?: string | string[]; + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route tags used for generating documentation + */ + tags?: string[]; +} + +/** + * Route public interface + * When route information is returned or made available as a property, it is an object with the following: + * [See docs](https://hapijs.com/api/16.1.1#route-public-interface) + */ +export interface RoutePublicInterface { + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | string[]; + /** the [active realm] [See docs](https://hapijs.com/api/16.1.1#serverrealm) associated with the route.*/ + realm: ServerRealm; + /** the [route options] [See docs](https://hapijs.com/api/16.1.1#route-options) object with all defaults applied. */ + settings: RouteAdditionalConfigurationOptions; + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + /** route authentication utilities: */ + auth: { + /** authenticates the passed request argument against the route's authentication access configuration. Returns true if the request would have passed the route's access requirements. Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. Also, if the route uses dynamic scopes, the scopes are constructed against the request.query and request.params which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or at all), it will return false if the route requires any authentication. */ + access(request: Request): boolean; + }; +} + +export type RouteHandlerConfig = any; + +/** + * For context [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/handler.js#L103) + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L56-L60) + * TODO check the type of `RouteHandlerConfig` is correct for `defaults`. + */ +export interface MakeRouteHandler { + (route: RoutePublicInterface, options: RouteHandlerConfig): RouteHandler; + defaults?: RouteHandlerConfig | ((method: HTTP_METHODS_PARTIAL_lowercase) => RouteHandlerConfig); +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value + */ +export interface RoutingTableEntry { + /** the connection.info the connection the table was generated for. */ + info: ServerConnectionInfo; + /** the connection labels. */ + labels: string[]; + /** an array of routes where each route contains: */ + table: Route[]; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value + */ +export interface Route { + /** + * the route config with defaults applied. + * TODO check type of RouteConfiguration here is correct + */ + settings: RouteConfiguration; + /** + * the HTTP method in lower case. + * TODO, check if it can contain 'head' or not. + */ + method: HTTP_METHODS_PARTIAL_lowercase; + /** the route path. */ + path: string; +} + +/** + * Route Prerequisites + * It is often necessary to perform prerequisite actions before the handler is called (e.g. load required reference data from a database). The route pre option allows defining such pre-handler methods. The methods are called in order. If the pre array contains another array, those methods are called in parallel. pre can be assigned a mixed array of: + * * arrays containing the elements listed below, which are executed in parallel. + * * objects see RoutePrerequisiteObjects + * * functions - same as including an object with a single method key. + * * strings - special short-hand notation for registered server methods using the format 'name(args)' (e.g. 'user(params.id)') where: + * * 'name' - the method name. The name is also used as the default value of assign. + * * 'args' - the method arguments (excluding next) where each argument is a property of the request object + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) + * For context see RouteAdditionalConfigurationOptions > pre + * + * TODO follow up on "server methods" in "special short-hand notation for registered server methods" at https://hapijs.com/api/16.1.1#servermethodname-method-options + * TODO follow up on "request object" in "each argument is a property of the request object" at https://hapijs.com/api/16.1.1#request-object + */ +export type RoutePrerequisitesArray = RoutePrerequisitesPart[] | (RoutePrerequisitesPart[] | RoutePrerequisitesPart)[]; +export type RoutePrerequisitesPart = RoutePrerequisiteObjects | RoutePrerequisiteRequestHandler | string; + +/** + * see RoutePrerequisites > objects + */ +export interface RoutePrerequisiteObjects { + /** the function to call (or short-hand method string as described below [see RoutePrerequisitesArray]). the function signature is identical to a route handler as described in Route handler. */ + method: RoutePrerequisiteRequestHandler | string; + /** key name to assign the result of the function to within request.pre. */ + assign: string; + /* + * determines how to handle errors returned by the method. Allowed values are: + * * 'error' - returns the error response back to the client. This is the default value. + * * 'log' - logs the error but continues processing the request. If assign is used, the error will be assigned. + * * 'ignore' - takes no special action. If assign is used, the error will be assigned. + */ + failAction?: 'error' | 'log' | 'ignore'; +} + +/** + * For context see RouteAdditionalConfigurationOptions > response + */ +export interface RouteResponseConfigurationObject { + /** the default HTTP status code when the payload is empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time or response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ + emptyStatusCode?: number; + /** + * defines what to do when a response fails payload validation. Options are: + * * 'error' - return an Internal Server Error (500) error response. This is the default value. + * * 'log' - log the error but send the response. + * * a custom error handler function with the signature function(request, reply, source, error) where: + * * 'request' - the request object. + * * 'reply' - the continuation reply interface. + * * 'error' - the error returned from the validation schema. + * TODO update type of source once PR to hapi is concluded. + */ + failAction?: 'error' | 'log' | ((request: Request, reply: ReplyWithContinue, source: string, error: Boom.BoomError) => void); + /** if true, applies the validation rule changes to the response payload. Defaults to false. */ + modify?: boolean; + /** options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is available [here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback) ). Defaults to no options. */ + options?: JoiValidationOptions; + /** if false, payload range support is disabled. Defaults to true. */ + ranges?: boolean; + /** the percent of response payloads validated (0 - 100). Set to 0 to disable all validation. Defaults to 100 (all response payloads). */ + sample?: number; + /** the default response payload validation rules (for all non-error responses) */ + schema?: RouteResponseConfigurationScheme; + /** HTTP status-code-specific payload validation rules. The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. If a response status code is not present in the status object, the schema definition is used, except for errors which are not validated by default. */ + status?: Dictionary; +} + +/** + * the default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation performed). This is the default. + * * false - no payload allowed. + * * a Joi validation object. This will receive the request's headers, params, query, payload, and auth credentials and isAuthenticated flags as context. + * * a validation function using the signature function(value, options, next) where: + * * value - the object containing the response object. + * * options - the server validation options, merged with an object containing the request's headers, params, payload, and auth credentials object and isAuthenticated flag. + * * next(err) - the callback function called when validation is completed. + * TODO check JoiValidationObject is correct for "a Joi validation object" + * + * For context see RouteAdditionalConfigurationOptions > response > schema + * and + * For context see RouteAdditionalConfigurationOptions > response > status + */ +export type RouteResponseConfigurationScheme = boolean | JoiValidationObject | ValidationFunctionForRouteReponse; + +/** + * see RouteResponseConfigurationScheme + * + * TODO check `value: Response` is correct as it says "**the object containing** the response object." not just "the response object". + * TODO check `options: JoiValidationOptions` is correct + * Also see ValidationFunctionForRouteValidate + */ +export interface ValidationFunctionForRouteReponse { + (value: Response, options: JoiValidationOptions, next: ContinuationFunction): void; +} + +/** + * For context see RouteAdditionalConfigurationOptions > security + */ +export interface RouteSecurityConfigurationObject { + /** controls the 'Strict-Transport-Security' header. If set to true the header will be set to max-age=15768000, if specified as a number the maxAge parameter will be set to that number. Defaults to true. You may also specify an object with the following fields: */ + hsts?: boolean | number | { + /** the max-age portion of the header, as a number. Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubDomains flag to the header. */ + includeSubdomains?: boolean; + /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ + preload?: boolean; + }; + /** controls the 'X-Frame-Options' header. When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'. Defaults to true. To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe?: true | 'deny' | 'sameorigin' | { + /** may also be 'deny' or 'sameorigin' but set directly as a string for xframe */ + rule: 'allow-from'; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE. Defaults to true which sets the header to equal '1; mode=block'. NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8. See [here](https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/) and [here](https://technet.microsoft.com/library/security/ms10-002) for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. [Kept typing non optional to force this security related documentation to be read.] */ + xss: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. */ + noOpen?: boolean; + /** boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff' */ + noSniff?: boolean; +} + +/** + * request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: + * For context see RouteAdditionalConfigurationOptions > validate + * TODO check JoiValidationObject is correct for "a Joi validation object" + */ +export interface RouteValidationConfigurationObject { + /** + * validation rules for incoming request headers (note that all header field names must be in lowercase to match the headers normalized by node). Values allowed: + * * true - any headers allowed (no validation performed). This is the default. + * * false - no headers allowed (this will cause all valid HTTP requests to fail). + * * a Joi validation object. + * * a validation function using the signature function(value, options, next) where: + * * value - the object containing the request headers. + * * options - the server validation options. + * * next(err, value) - the callback function called when validation is completed. + */ + headers?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + /** + * validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params. Values allowed: + * Same as `headers`, see above. + */ + params?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + /** + * validation rules for an incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs and stored in request.query prior to validation. Values allowed: + * Same as `headers`, see above. + */ + query?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + /** + * validation rules for an incoming request payload (request body). Values allowed: + * Same as `headers`, see above, with the addition that: + * * a Joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are supported, it must be explicitly defined by setting the payload value to a joi schema with null allowed (e.g. Joi.object({ /* keys here * / }).allow(null)). + */ + payload?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** + * determines how to handle invalid requests. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - log the error but continue processing the request. + * * 'ignore' - take no action. + * * a custom error handler function with the signature function(request, reply, source, error) see RouteFailFunction + */ + failAction?: 'error' | 'log' | 'ignore' | RouteFailFunction; + /** options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is [available here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)). Defaults to no options. */ + options?: JoiValidationOptions; +} + +/** + * a validation function using the signature function(value, options, next) where: + * For context see RouteAdditionalConfigurationOptions > validate (IRouteValidationConfigurationObject) + * + * TODO check `value: Response` is correct as it says "**the object containing** the response object." not just "the response object". + * TODO check `options: JoiValidationOptions` is correct + * TODO type of the returned value? + * Also see ValidationFunctionForRouteReponse + * @param value - the object containing the request headers. + * @param options - the server validation options. + * @param next(err, value) - the callback function called when validation is completed. + */ +export interface ValidationFunctionForRouteValidate { + (value: Response, options: JoiValidationOptions, next: ContinuationValueFunction): void; +} + +/** + * a custom error handler function with the signature 'function(request, reply, source, error)` + * @param request - the request object. + * @param reply - the continuation reply interface. + * @param source - the source of the invalid field (e.g. 'headers', 'params', 'query', 'payload'). + * @param error - the error object prepared for the client response (including the validation function error under error.data). + */ +export interface RouteFailFunction { + (request: Request, reply: ReplyWithContinue, source: string, error: any): void; +} + +/** + * optional cookie settings + * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) + * Related to see ConnectionConfigurationServerDefaults + */ +export interface ServerStateCookieConfiguationObject { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag where the value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + * * request - the request object. + * * next - the continuation function using the function(err, value) signature. + */ + autoValue?(request: Request, next: ContinuationValueFunction): void; + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: any; // TODO make iron definitions and getting typing from iron + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: any; // TODO make iron definitions and getting typing from iron + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverconnections) + */ +export interface ServerConnection { + /** settings - the connection configuration object passed to server.connection() after applying the server defaults. */ + settings: ServerConnectionOptions; + /** server - the connection's Server object. */ + server: Server; + /** type - set to 'tcp' is the connection is listening on a TCP port, otherwise to 'socket'(a UNIX domain socket or a Windows named pipe). */ + type: 'tcp' | 'socket'; + /** + * registrations + * Described [See docs](https://hapijs.com/api/16.1.1#serverregistrations) "When the server contains more than one connection, each server.connections array member provides its own connection.registrations." + */ + registrations: ServerRegisteredPlugins; + /** states - TODO contribute docs to hapi if they want, and then update type here */ + states: any; + /** auth - TODO contribute docs to hapi if they want, and then update type here */ + auth: any; + /** + * plugins + * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc + */ + plugins: PluginsStates; + /** + * app + * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc + */ + app: any; + /** Described in server.listener [See docs](https://hapijs.com/api/16.1.1#serverlistener) */ + listener: ServerListener; + /** Described in server.info [See docs](https://hapijs.com/api/16.1.1#serverinfo) */ + info: ServerConnectionInfo; + /** Described in server.inject [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) */ + inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; + inject(options: string | InjectedRequestOptions, ): Promise; + /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servertablehost) */ + table(host?: string): RoutingTableEntry; + /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#serverlookupid) */ + lookup(id: string): RoutePublicInterface | null; + /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) */ + match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverinfo) + */ +export interface ServerConnectionInfo { + /** a unique connection identifier (using the format '{hostname}:{pid}:{now base36}'). */ + id: string; + /** the connection creation timestamp. */ + created: number; + /** the connection start timestamp (0 when stopped). */ + started: number; + /** + * the connection port based on the following rules: + * * the configured port value before the server has been started. + * * the actual port assigned when no port is configured or set to 0 after the server has been started. + * TODO check this type. What happens when socket is a UNIX domain socket or Windows named pipe? + */ + port: number | string; + /** the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'. */ + host: string; + /** the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). */ + address: undefined | string; + /** the protocol used. 'socket' when UNIX domain socket or Windows named pipe. */ + protocol: 'http' | 'https' | 'socket'; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component. */ + uri: string; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverlistener) + */ +export type ServerListener = http.Server; + +/** + * server.realm + * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + * [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include the trailing slash. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: any; // OptionsPassedToPlugin; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides (from RouteAdditionalConfigurationOptions) */ + settings: { + files: { + relativeTo: string; + }; + bind: any; + }; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ +export interface ServerRegisteredPlugins { + [pluginName: string]: ServerRegisteredPlugin; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ +export interface ServerRegisteredPlugin { + /** the plugin version. */ + version: string; + /** the plugin name. */ + name: string; + /** + * options used to register the plugin. + * TODO update with outcome of: https://github.com/hapijs/hapi/pull/3479 + */ + options: any; // OptionsPassedToPlugin; + /** plugin registration attributes. */ + attributes: PluginAttributes; +} + +export interface ServerAuth { + /** + * server.auth.api + * An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. + * When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. + * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) + */ + api: Dictionary; + /** + * server.auth.default + * Sets a default strategy which is applied to every route + * The default does not apply when the route config specifies auth as false, or has an authentication strategy configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication config is applied to the defaults. + * Note that if the route has authentication config, the default only applies at the time of adding the route, not at runtime. This means that calling default() after adding a route with some authentication config will have no impact on the routes added prior. However, the default will apply to routes added before default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via connection.auth.settings.default. To obtain the active authentication configuration of a route, use connection.auth.lookup(request.route). + * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) + */ + default(options: string | AuthOptions): void; + /** + * server.auth.scheme + * Registers an authentication scheme + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * @param name the scheme name. + * @param scheme the method implementing the scheme with signature function(server, options) see ServerAuthScheme + */ + scheme(name: string, scheme: ServerAuthScheme): void; + /** + * Registers an authentication strategy + * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) + * @param name the strategy name. + * @param scheme the scheme name (must be previously registered using server.auth.scheme()). + * @param mode if set to true (which is the same as 'required') or to a valid authentication mode ('required', 'optional', 'try'), the scheme is automatically assigned as the default strategy for any route without an auth config. Can only be assigned to a single server strategy. Defaults to false (no default settings). + * @param options scheme options based on the scheme requirements. + */ + strategy(name: string, scheme: string, options?: any): void; + strategy(name: string, scheme: string, mode: boolean | 'required' | 'optional' | 'try', options?: any): void; + /** + * Tests a request against an authentication strategy + * Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @param next - the callback function with signature function(err, credentials) where: + * * err - the error if authentication failed. + * * credentials - the authentication credentials object if authentication was successful. + */ + test(strategy: string, request: Request, next: (err: Error | null, credentials: AuthenticatedCredentials) => void): void; +} + +export type Strategy = any; +export type SchemeSettings = any; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * @param server a reference to the server object the scheme is added to. + * @param options optional scheme settings used to instantiate a strategy. + */ +export interface ServerAuthScheme { + (server: Server, options: SchemeSettings): SchemeMethodResult; +} + +/** + * The scheme method must return an object with the following + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + */ +export interface SchemeMethodResult { + /** optional object which is exposed via the server.auth.api object. */ + api?: Strategy; + /** + * required function called on each incoming request configured with the authentication scheme + * When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted (if configured for the route). If the err passed to the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include the scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in the order of preference (defined in the route configuration). If authentication fails the scheme names will be present in the 'WWW-Authenticate' header. + * @param request the request object. + * @param reply the reply interface the authentication method must call when done authenticating the request + */ + authenticate(request: Request, reply: ReplySchemeAuth): void; + /** + * optional function called to authenticate the request payload + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param reply is called if authentication failed + */ + payload?(request: Request, reply: ReplySchemeAuthOfPayload): void; + /** + * optional function called to decorate the response with authentication headers before the response headers or payload is written where: + * @param request the request object. + * @param reply is called if an error occured + */ + response?(request: Request, reply: ReplySchemeAuthDecorateResponse): void; + /** an optional object with the following keys: */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. */ + payload?: boolean; + }; +} + +export interface ServerCacheMethod { + /** + * Provisions a cache segment within the server cache facility + * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + */ + (options: CatboxServerCacheConfiguration): Catbox.Policy; + /** + * Provisions a server cache as described in server.cache + * If no callback is provided, a Promise object is returned. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) + * @param options same as the server cache configuration options. + * @param callback the callback method when cache provisioning is completed or failed with the signature function(err) where: + * * err - any cache startup error condition. + */ + provision(options: CatboxServerCacheConfiguration): Promise; + provision(options: CatboxServerCacheConfiguration, callback: (err?: Error) => void): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Request object + * The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + * [See docs](https://hapijs.com/api/16.1.1#request-object) + * [See docs](https://hapijs.com/api/16.1.1#request-properties) + */ +export class Request extends Podium { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ + app: any; + /** authentication information */ + auth: { + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: any; + /** the route authentication mode. */ + mode: string; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; + }; + /** the connection the request was received by. */ + connection: ServerConnection; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains. Set to null when the server useDomains options is false. */ + domain: domain.Domain | null; + /** the raw request headers (references request.raw.headers). */ + headers: Dictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: string; + /** request information */ + info: { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * Note: marking as optional as "... this is only available after ..." + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** + * remote client port. + * Set to string in casethey're requesting from a UNIX domain socket. + * TODO, what type does Hapi return, should this be number | string? + */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. */ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters [See docs](https://hapijs.com/api/16.1.1#path-parameters). */ + params: Dictionary; + /** an array containing all the path params values in the order they appeared in the path. */ + paramsArray: string[]; + /** the request URI's pathname [See docs](https://nodejs.org/api/url.html#url_urlobject_pathname) component. */ + path: string; + /** + * the request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + payload: stream.Readable | Buffer | any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: PluginsStates; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ + pre: Object; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). */ + response: Response | null; + /** same as pre but represented as the response object created by the pre method. */ + preResponses: Object; + /** + * an object containing the query parameters. + * TODO update with outcome of: https://github.com/hapijs/hapi/pull/3479 + */ + query: Object; + /** an object containing the Node HTTP server objects. **Direct interaction with these raw objects is not recommended.** */ + raw: { + req: http.IncomingMessage; // Or http.ClientRequest http://www.apetuts.com/tutorial/node-js-http-client-request-class/ ? + res: http.ServerResponse; + }; + /** + * the route public interface. + * Optional due to "request.route is not yet populated at this point." [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) + */ + route?: RoutePublicInterface; + /** the server object. */ + server: Server; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: Dictionary; + /** the parsed request URI */ + url: url.Url; + + /** + * request.setUrl(url, [stripTrailingSlash]) + * Available only in 'onRequest' extension methods. + * Changes the request URI before the router begins processing the request + * [See docs](https://hapijs.com/api/16.1.1#requestseturlurl-striptrailingslash) + * @param url the new request URI. If url is a string, it is parsed with node's URL parse() method. url can also be set to an object compatible with node's URL parse() method output. + * @param stripTrailingSlash if true, strip the trailing slash from the path. Defaults to false. + */ + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; + /** + * request.setMethod(method) + * Available only in 'onRequest' extension methods. + * Changes the request method before the router begins processing the request + * [See docs](https://hapijs.com/api/16.1.1#requestsetmethodmethod) + * @param method is the request HTTP method (e.g. 'GET'). + */ + setMethod(method: HTTP_METHODS): void; + /** + * request.generateResponse(source, [options]) + * Always available. + * Returns a response which you can pass into the reply interface where: + * [See docs](https://hapijs.com/api/16.1.1#requestgenerateresponsesource-options) + * @param source the object to set as the source of the reply interface. TODO, submit a PR to clarify this doc, from the source code it's clear that "the object to set" refers to something of type `ReplyValue` i.e. that can be null, string, number, object, Stream, Promise, or Buffer. + * @param options options for the method, optional. Not documented yet, perhaps not very important. + */ + generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): Response; + /** + * request.log(tags, [data, [timestamp]]) + * Always available. + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. + * Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + * [See docs](https://hapijs.com/api/16.1.1#requestlogtags-data-timestamp) + * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. + * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. + * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + */ + log(tags: string | string[], data?: string | Object | (() => string | Object), timestamp?: number): void; + /** + * request.getLog([tags], [internal]) + * Always available. + * Returns an array containing the events matching any of the tags specified (logical OR) + * Note that this methods requires the route log configuration set to true. + * [See docs](https://hapijs.com/api/16.1.1#requestgetlogtags-internal) + * @param tags is a single tag string or array of tag strings. If no tags specified, returns all events. + * @param internal filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined). + */ + getLog(tags?: string | string[], internal?: boolean): string[]; + getLog(internal?: boolean): string[]; + /** + * request.tail([name]) + * Available until immediately after the 'response' event is emitted. + * Adds a request tail which has to complete before the request lifecycle is complete. + * Returns a tail function which must be called when the tail activity is completed. + * Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + * When all tails completed, the server emits a 'tail' event. + * [See docs](https://hapijs.com/api/16.1.1#requesttailname) + * @param name an optional tail name used for logging purposes. + */ + tail(name?: string): (() => void); + /** + * The server.decorate('request', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; +} + +export type HTTP_METHODS_PARTIAL_lowercase = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; +export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_lowercase; +export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; + +/** + * Request events + * The request object supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://hapijs.com/api/16.1.1#request-events) + */ +export type RequestEventTypes = 'peek' | 'finish' | 'disconnect'; + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Handler functions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Extending RouteConfiguration.handler + * + * The hapi documentation allows for the RouteConfiguration.handler type to have + * `{[pluginName: string]: pluginOptions}` + * "handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler" + * This can be provided by extending the hapi module definition as follows, + * see h2o2 for example: + * + * declare module 'hapi' { + * interface RouteHandlerPlugins { + * proxy?: ... + */ +export interface RouteHandlerPlugins { } /** - * undocumented. The connection object constructed after calling server.connection(); - * can be accessed via server.connections; or request.connection; + * The route handler function uses the signature function(request, reply) (NOTE: do not use a fat arrow style function for route handlers as they do not allow context binding and will cause problems when used in conjunction with server.bind) where: + * * request - is the incoming request object (this is not the node.js request object). + * * reply - the reply interface the handler must call to set a response and return control back to the framework. + * [See docs](https://hapijs.com/api/16.1.1#route-handler) + * Same function signature used by request extension point used in server.ext(event), see ServerExtConfigurationObject.method */ -export class ServerConnection extends Events.EventEmitter { - domain: any; - _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; - _eventsCount: number; - settings: IServerConnectionOptions; - server: Server; - /** ex: "tcp" */ - type: string; - _started: boolean; - /** dictionary of sockets */ - _connections: { [ip_port: string]: any }; - _onConnection: Function; - registrations: any; - _extensions: any; - _requestCounter: { value: number; min: number; max: number }; - _load: any; - states: { - settings: any; cookies: any; names: any[] - }; - auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; }; - _router: any; - MSPluginsCollection: any; - applicationCache: any; - addEventListener: any; - info: IServerConnectionInfo; +export interface RouteHandler { + (request: Request, reply: ReplyNoContinue): void; + // (request: Request, reply: StrictReply): void; } -export type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; -export type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; +/** + * "the function to call, the function signature is identical to a route handler as described in Route handler." + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) Route prerequisites + */ +export type RoutePrerequisiteRequestHandler = RouteHandler; -/** Server http://hapijs.com/api#server - rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). - Server events - The server object inherits from Events.EventEmitter and emits the following events: - 'log' - events logged with server.log() and server events generated internally by the framework. - 'start' - emitted when the server is started using server.start(). - 'stop' - emitted when the server is stopped using server.stop(). - 'request' - events generated by request.log(). Does not include any internally generated events. - 'request-internal' - request events generated internally by the framework (multiple events per request). - 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. - 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. - 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. - Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. - MORE EVENTS HERE: http://hapijs.com/api#server-events*/ -export class Server extends Events.EventEmitter { - constructor(options?: IServerOptions); - - /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. - var Hapi = require('hapi'); - server = new Hapi.Server(); - server.app.key = 'value'; - var handler = function (request, reply) { - return reply(request.server.app.key); - }; */ - app: any; - /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. - var server = new Hapi.Server(); - server.connection({ port: 80, labels: 'a' }); - server.connection({ port: 8080, labels: 'b' }); - // server.connections.length === 2 - var a = server.select('a'); - // a.connections.length === 1*/ - connections: ServerConnection[]; - /** When the server contains exactly one connection, info is an object containing information about the sole connection. - * When the server contains more than one connection, each server.connections array member provides its own connection.info. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // server.info.port === 80 - server.connection({ port: 8080 }); - // server.info === null - // server.connections[1].info.port === 8080 - */ - info: IServerConnectionInfo; - /** An object containing the process load metrics (when load.sampleInterval is enabled): - rss - RSS memory usage. - var Hapi = require('hapi'); - var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); - console.log(server.load.rss);*/ - load: { - /** - event loop delay milliseconds.*/ - eventLoopDelay: number; - /** - V8 heap usage.*/ - heapUsed: number; - }; - /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. - When the server contains more than one connection, each server.connections array member provides its own connection.listener. - var Hapi = require('hapi'); - var SocketIO = require('socket.io'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var io = SocketIO.listen(server.listener); - io.sockets.on('connection', function(socket) { - socket.emit({ msg: 'welcome' }); - });*/ - listener: http.Server; - - /** server.methods - An object providing access to the server methods where each server method name is an object property. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.method('add', function (a, b, next) { - return next(null, a + b); - }); - server.methods.add(1, 2, function (err, result) { - // result === 3 - });*/ - methods: IDictionary; - - /** server.mime - Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. - var Hapi = require('hapi'); - var options = { - mime: { - override: { - 'node/module': { - source: 'steve', - compressible: false, - extensions: ['node', 'module', 'npm'], - type: 'node/module' - } - } - } - }; - var server = new Hapi.Server(options); - // server.mime.path('code.js').type === 'application/javascript' - // server.mime.path('file.npm').type === 'node/module'*/ - mime: any; - /**server.plugins - An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. - exports.register = function (server, options, next) { - server.expose('key', 'value'); - // server.plugins.example.key === 'value' - return next(); - }; - exports.register.attributes = { - name: 'example' - };*/ - plugins: IDictionary; - /** server.realm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: - route - routes preferences: - prefix - the route path prefix used by any calls to server.route() from the server. - vhost - the route virtual host settings used by any calls to server.route() from the server. - plugin - the active plugin name (empty string if at the server root). - plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. - settings - settings overrides: - files.relativeTo - bind - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { - console.log(server.realm.modifiers.route.prefix); - return next(); - };*/ - realm: IServerRealm; - - /** server.root - The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ - root: Server; - /** server.settings - The server configuration object after defaults applied. - var Hapi = require('hapi'); - var server = new Hapi.Server({ - app: { - key: 'value' - } - }); - // server.settings.app === { key: 'value' }*/ - settings: IServerOptions; - - /** server.version - The hapi module version number. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - // server.version === '8.0.0'*/ - version: string; - - /** server.after(method, [dependencies]) - Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: - after - the method with signature function(plugin, next) where: - server - server object the after() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error which is returned back via the server.start() callback. - dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.after(function () { - // Perform some pre-start logic - }); - server.start(function (err) { - // After method already executed - }); - server.auth.default(options)*/ - after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; - - auth: { - /** server.auth.api - An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. - When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. - const server = new Hapi.Server(); - server.connection({ port: 80 }); - const scheme = function (server, options) { - return { - api: { - settings: { - x: 5 - } - }, - authenticate: function (request, reply) { - const req = request.raw.req; - const authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply.continue({ credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - console.log(server.auth.api.default.settings.x); // 5 - */ - api: { - [index: string]: any; - } - /** server.auth.default(options) - Sets a default strategy which is applied to every route where: - options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. - The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. - The default auth strategy configuration can be accessed via connection.auth.settings.default. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.auth.default('default'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply(request.auth.credentials.user); - } - });*/ - default(options: string): void; - default(options: { strategy: string }): void; - default(options: { strategies: string[] }): void; - /** server.auth.scheme(name, scheme) - Registers an authentication scheme where: - name - the scheme name. - scheme - the method implementing the scheme with signature function(server, options) where: - server - a reference to the server object the scheme is added to. - options - optional scheme settings used to instantiate a strategy.*/ - scheme( - name: string, - /** - * When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - * n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. - * server = new Hapi.Server(); - * server.connection({ port: 80 }); - * scheme = function (server, options) { - * urn { - * authenticate: function (request, reply) { - * req = request.raw.req; - * var authorization = req.headers.authorization; - * if (!authorization) { - * return reply(Boom.unauthorized(null, 'Custom')); - * } - * urn reply(null, { credentials: { user: 'john' } }); - * } - * }; - * }; - */ - scheme: (server: Server, options: any) => IServerAuthScheme): void; - - /** - * server.auth.strategy(name, scheme, [mode], [options]) - * Registers an authentication strategy where: - * name - the strategy name. - * scheme - the scheme name (must be previously registered using server.auth.scheme()). - * mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. - * options - scheme options based on the scheme requirements. - * var server = new Hapi.Server(); - * server.connection({ port: 80 }); - * server.auth.scheme('custom', scheme); - * server.auth.strategy('default', 'custom'); - * server.route({ - * method: 'GET', - * path: '/', - * config: { - * auth: 'default', - * handler: function (request, reply) { - * return reply(request.auth.credentials.user); - * } - * } - * }); - */ - strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; - strategy(name: string, scheme: string, mode?: boolean | string): void; - strategy(name: string, scheme: string, options?: any): void; - - /** server.auth.test(strategy, request, next) - Tests a request against an authentication strategy where: - strategy - the strategy name registered with server.auth.strategy(). - request - the request object. - next - the callback function with signature function(err, credentials) where: - err - the error if authentication failed. - credentials - the authentication credentials object if authentication was successful. - Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - request.server.auth.test('default', request, function (err, credentials) { - if (err) { - return reply({ status: false }); - } - return reply({ status: true, user: credentials.name }); - }); - } - });*/ - test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; - }; - - /** server.bind(context) - Sets a global context used as the default bind object when adding a route or an extension where: - context - the object used to bind this in handler and extension methods. - When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. - var handler = function (request, reply) { - return reply(this.message); - }; - exports.register = function (server, options, next) { - var bind = { - message: 'hello' - }; - server.bind(bind); - server.route({ method: 'GET', path: '/', handler: handler }); - return next(); - };*/ - bind(context: any): void; - - /** server.cache(options) - Provisions a cache segment within the server cache facility where: - options - catbox policy configuration where: - expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. - generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. - staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. - staleTimeout - number of milliseconds to wait before checking if an item is stale. - generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. - cache - the cache name configured in 'server.cache`. Defaults to the default cache. - segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. - shared - if true, allows multiple cache provisions to share the same segment. Default to false. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); - cache.set('norway', { capital: 'oslo' }, null, function (err) { - cache.get('norway', function (err, value, cached, log) { - // value === { capital: 'oslo' }; - }); - });*/ - cache(options: ICatBoxCachePolicyOptions): void; - - /** server.connection([options]) - Adds an incoming server connection - Returns a server object with the new connection selected. - Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). - Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); - var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); - // server.connections.length === 2 - // web.connections.length === 1 - // admin.connections.length === 1 */ - connection(options: IServerConnectionOptions): Server; - - /** server.decorate(type, property, method, [options]) - Extends various framework interfaces with custom methods where: - type - the interface being decorated. Supported types: - 'reply' - adds methods to the reply interface. - 'server' - adds methods to the Server object. - property - the object decoration key name. - method - the extension function. - options - if the type is 'request', supports the following optional settings: - 'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. - Note that decorations apply to the entire server and all its connections regardless of current selection. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.decorate('reply', 'success', function () { - return this.response({ status: 'ok' }); - }); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply.success(); - } - });*/ - decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void; - - /** server.dependency(dependencies, [after]) - Used within a plugin to declares a required dependency on other plugins where: - dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. - after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: - server - the server the dependency() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error condition, which is returned back via the server.start() callback. - exports.register = function (server, options, next) { - server.dependency('yar', after); - return next(); - }; - var after = function (server, next) { - // Additional plugin registration logic - return next(); - };*/ - dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; - - /** server.expose(key, value) - Used within a plugin to expose a property via server.plugins[name] where: - key - the key assigned (server.plugins[name][key]). - value - the value assigned. - exports.register = function (server, options, next) { - server.expose('util', function () { console.log('something'); }); - return next(); - };*/ - expose(key: string, value: any): void; - - /** server.expose(obj) - Merges a deep copy of an object into to the existing content of server.plugins[name] where: - obj - the object merged into the exposed properties container. - exports.register = function (server, options, next) { - server.expose({ util: function () { console.log('something'); } }); - return next(); - };*/ - expose(obj: any): void; - - /** server.ext(event, method, [options]) - Registers an extension function in one of the available extension points where: - event - the event name. - method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: - request - the request object. NOTE: Access the Response via request.response - reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. - this - the object provided via options.bind or the current active context set with server.bind(). - options - an optional object with the following: - before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - bind - a context object passed back to the provided method (via this) when called. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.ext('onRequest', function (request, reply) { - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - }); - var handler = function (request, reply) { - return reply({ status: 'ok' }); - }; - server.route({ method: 'GET', path: '/test', handler: handler }); - server.start(); - // All requests will get routed to '/test'*/ - ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - - /** server.handler(name, method) - Registers a new handler type to be used in routes where: - name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. - method - the function used to generate the route handler using the signature function(route, options) where: - route - the route public interface object. - options - the configuration object provided in the handler config. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - // Defines new handler for routes on this server - server.handler('test', function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }); - server.route({ - method: 'GET', - path: '/', - handler: { test: { msg: 'test' } } - }); - server.start(); - The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - var handler = function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }; - // Change the default payload processing for this handler - handler.defaults = { - payload: { - output: 'stream', - parse: false - } - }; - server.handler('test', handler);*/ - handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; - - /** server.initialize([callback]) - Initializes the server (starts the caches, finalizes plugin registration) but does not start listening - on the connection ports, where: - - `callback` - the callback method when server initialization is completed or failed with the signature - `function(err)` where: - - `err` - any initialization error condition. - - If no `callback` is provided, a `Promise` object is returned. - - Note that if the method fails and the callback includes an error, the server is considered to be in - an undefined state and should be shut down. In most cases it would be impossible to fully recover as - the various plugins, caches, and other event listeners will get confused by repeated attempts to - start the server or make assumptions about the healthy state of the environment. It is recommended - to assert that no error has been returned after calling `initialize()` to abort the process when the - server fails to start properly. If you must try to resume after an error, call `server.stop()` - first to reset the server state. - */ - initialize(callback?: (error: any) => void): Promise; - - /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. - Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. - Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties - * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var handler = function (request, reply) { - return reply('Success!'); - }; - server.route({ method: 'GET', path: '/', handler: handler }); - server.inject('/', function (res) { - console.log(res.result); - }); - */ - inject: IServerInject; - - /** server.log(tags, [data, [timestamp]]) - Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: - tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('log', function (event, tags) { - if (tags.error) { - console.log(event); - } - }); - server.log(['test', 'error'], 'Test event');*/ - log(tags: string | string[], data?: string | any, timestamp?: number): void; - - /**server.lookup(id) - When the server contains exactly one connection, looks up a route configuration where: - id - the route identifier as set in the route options. - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.lookup('root'); - When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ - lookup(id: string): IRoute; - - /** server.match(method, path, [host]) - When the server contains exactly one connection, looks up a route configuration where: - method - the HTTP method (e.g. 'GET', 'POST'). - path - the requested path (must begin with '/'). - host - optional hostname (to match against routes with vhost). - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.match('get', '/'); - When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ - match(method: string, path: string, host?: string): IRoute; - - /** server.method(name, method, [options]) - Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. - Methods are registered via server.method(name, method, [options]) - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Simple arguments - var add = function (a, b, next) { - return next(null, a + b); - }; - server.method('sum', add, { cache: { expiresIn: 2000 } }); - server.methods.sum(4, 5, function (err, result) { - console.log(result); - }); - // Object argument - var addArray = function (array, next) { - var sum = 0; - array.forEach(function (item) { - sum += item; - }); - return next(null, sum); - }; - server.method('sumObj', addArray, { - cache: { expiresIn: 2000 }, - generateKey: function (array) { - return array.join(','); - } - }); - server.methods.sumObj([5, 6], function (err, result) { - console.log(result); - }); - // Synchronous method with cache - var addSync = function (a, b) { - return a + b; - }; - server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); - server.methods.sumSync(4, 5, function (err, result) { - console.log(result); - }); */ - method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ - name: string, - method: IServerMethod, - options?: IServerMethodOptions): void; - - /**server.method(methods) - Registers a server method function as described in server.method() using a configuration object where: - methods - an object or an array of objects where each one contains: - name - the method name. - method - the method function. - options - optional settings. - var add = function (a, b, next) { - next(null, a + b); - }; - server.method({ - name: 'sum', - method: add, - options: { - cache: { - expiresIn: 2000 - } - } - });*/ - method(methods: { - name: string; method: IServerMethod; options?: IServerMethodOptions - } | Array<{ - name: string; method: IServerMethod; options?: IServerMethodOptions - }>): void; - - /**server.path(relativeTo) - Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: - relativeTo - the path prefix added to any relative file path starting with '.'. - Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. - exports.register = function (server, options, next) { - server.path(__dirname + '../static'); - server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); - next(); - };*/ - path(relativeTo: string): void; - - /** - * server.register(plugins, [options], callback) - * Registers a plugin where: - * plugins - an object or array of objects where each one is either: - * a plugin registration function. - * an object with the following: - * register - the plugin registration function. - * options - optional options passed to the registration function when called. - * options - optional registration options (different from the options passed to the registration function): - * select - a string or array of string labels used to pre-select connections for plugin registration. - * routes - modifiers applied to each route added by the plugin: - * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * callback - the callback function with signature function(err) where: - * err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. - * - * If no callback is provided, a Promise object is returned. - */ - register( - plugins: any | any[], - options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }, - callback: (err: any) => void): void; - register( - plugins: any | any[], - options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }): Promise; - - register(plugins: any | any[], callback: (err: any) => void): void; - register(plugins: any | any[]): Promise; - - /**server.render(template, context, [options], callback) - Utilizes the server views manager to render a template where: - template - the template filename and path, relative to the views manager templates path (path or relativeTo). - context - optional object used by the template to render context-specific result. Defaults to no context ({}). - options - optional object used to override the views manager configuration. - callback - the callback function with signature function (err, rendered, config) where: - err - the rendering error if any. - rendered - the result view string. - config - the configuration used to render the template. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.views({ - engines: { html: require('handlebars') }, - path: __dirname + '/templates' - }); - var context = { - title: 'Views Example', - message: 'Hello, World' - }; - server.render('hello', context, function (err, rendered, config) { - console.log(rendered); - });*/ - render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; - - /** server.route(options) - Adds a connection route where: - options - a route configuration object or an array of configuration objects. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); - server.route([ - { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, - { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } - ]);*/ - route(options: IRouteConfiguration): void; - route(options: IRouteConfiguration[]): void; - - /**server.select(labels) - Selects a subset of the server's connections where: - labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. - Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, labels: ['a'] }); - server.connection({ port: 8080, labels: ['b'] }); - server.connection({ port: 8081, labels: ['c'] }); - server.connection({ port: 8082, labels: ['c','d'] }); - var a = server.select('a'); // The server with port 80 - var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 - var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ - select(labels: string | string[]): Server | Server[]; - - /** server.start([callback]) - Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: - callback - optional callback when server startup is completed or failed with the signature function(err) where: - err - any startup error condition. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.start(function (err) { - console.log('Server started at: ' + server.info.uri); - });*/ - start(callback?: (err: any) => void): Promise; - - /** server.state(name, [options]) - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions - State defaults can be modified via the server connections.routes.state configuration option. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Set cookie definition - server.state('session', { - ttl: 24 * 60 * 60 * 1000, // One day - isSecure: true, - path: '/', - encoding: 'base64json' - }); - // Set state in route handler - var handler = function (request, reply) { - var session = request.state.session; - if (!session) { - session = { user: 'joe' }; - } - session.last = Date.now(); - return reply('Success').state('session', session); - }; - Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('request-internal', function (request, event, tags) { - if (tags.error && tags.state) { - console.error(event); - } - }); */ - state(name: string, options?: ICookieSettings): void; - - /** server.stop([options], [callback]) - Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: - options - optional object with: - timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). - callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.stop({ timeout: 60 * 1000 }, function () { - console.log('Server stopped'); - });*/ - stop(options?: { timeout: number }, callback?: () => void): Promise; - - /**server.table([host]) - Returns a copy of the routing table where: - host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path. - Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.table(); - When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.connections[0].table(); - //[ - // { - // method: 'get', - // path: '/example', - // settings: { ... } - // } - //] - */ - table(host?: any): IConnectionTable; - - /**server.views(options) - Initializes the server views manager - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.views({ - engines: { - html: require('handlebars'), - jade: require('jade') - }, - path: '/static/templates' - }); - When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ - views(options: IServerViewsConfiguration): void; +/** + * request extension points: function(request, reply) where + * this - the object provided via options.bind or the current active context set with server.bind(). + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * @param request the request object. + * @param reply the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. If the extension type is 'onPostHandler' or 'onPreResponse', a single argument passed to reply.continue() will override the current set response (including all headers) but will not stop the request lifecycle execution. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + */ +export interface ServerExtRequestHandler { + (request: Request, reply: ReplyWithContinue): void; +} + +/** + * Used by various extensions to handle a request and + * synchronously return a result of some form. + * + * Left in for backwards compatibility of typings but according to the + * [DefinitelyTyped Readme under common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes) + * it talks about not using generic types unless the type was used in typing one + * or more of the function arguments. Using it to type the return was suggested + * to be the same as a type assertion. + */ +export interface RequestHandler { + (request: Request): T; +} + +/** + * Used by server extension points + * err can be BoomError or Error that will be wrapped as a BoomError + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/reply.js#L109-L118) + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) + */ +export interface ContinuationFunction { + (err: Boom.BoomError): void; +} +/** + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) + * TODO Can value be typed with a useful generic? + */ +export interface ContinuationValueFunction { + (err: Boom.BoomError, value: any): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reply functions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Typings listed explicitly here [See docs](https://hapijs.com/api/16.1.1#replyerr-result) + * Typings also described in part here [See docs](https://hapijs.com/api/16.1.1#response-object) + */ +export type ReplyValue = _ReplyValue | Promise<_ReplyValue>; +export type _ReplyValue = null | undefined | string | number | boolean | Buffer | Error | stream.Stream | Object; // | array; + +/** + * Reply interface + * reply([err], [result]) + * Concludes the handler activity by setting a response and returning control over to the framework + * When reply() is called with an error or result response, that value is used as the response sent to the client. When reply() is called within a prerequisite, the value is saved for future use and is not used as the response. In all other places except for the handler, calling reply() will be considered an error and will abort the request lifecycle, jumping directly to the 'onPreResponse' event. + * To return control to the framework within an extension or other places other than the handler, without setting a response, the method reply.continue() must be called. Except when used within an authentication strategy, or in an 'onPostHandler' or 'onPreResponse' extension, the reply.continue() must not be passed any argument or an exception is thrown. + * [See docs](https://hapijs.com/api/16.1.1#reply-interface) + * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) + * + * NOTE: modules should extend this interface to expose reply.Nnn methods + */ +export interface Base_Reply { + (err?: ReplyValue): Response; + (err: null, result?: ReplyValue): Response; + /** the active realm associated with the route. */ + realm: ServerRealm; + /** the request object */ + request: Request; + + /** + * reply.entity(options) + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request conditions, reply.entity() returns control back to the framework with a 304 response. Otherwise, it sets the provided entity headers and returns null. + * Returns a response object if the reply is unmodified or null if the response has changed. If null is returned, the developer must call reply() to continue execution. If the response is not null, the developer must not call reply(). + * [See docs](https://hapijs.com/api/16.1.1#replyentityoptions) + * @param options a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + */ + entity(options: {etag?: string, modified?: string, vary?: boolean}): Response | null; + /** + * reply.close([options]) + * Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed. Supports the following optional options: + * The response flow control rules do not apply. + * [See docs](https://hapijs.com/api/16.1.1#replycloseoptions) + * @param options options object: + * * end - if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. + */ + close(options?: {end?: boolean}): void; + /** + * reply.redirect(uri) + * Redirects the client to the specified uri. Same as calling reply().redirect(uri). + * The response flow control rules apply. + * Sets an HTTP redirection response (302) and decorates the response with additional methods for + * changing to a permanent or non-rewritable redirect is also available see response object redirect for more information. + * [See docs](https://hapijs.com/api/16.1.1#replyredirecturi) + * @param uri an absolute or relative URI used to redirect the client to another resource. + */ + redirect(uri: string): ResponseRedirect; + /** + * reply.response(result) + * Shorthand for calling `reply(null, result)`, replies with the response set to `result`. + * [See docs](https://hapijs.com/api/16.1.1#replyresponseresult) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + response(result: ReplyValue): Response; + /** + * Sets a cookie on the response + * [See docs](https://hapijs.com/api/16.1.1#reply) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + state(name: string, value: any, options?: any): void; + /** + * Clears a cookie on the response + * [See docs](https://hapijs.com/api/16.1.1#reply) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + unstate(name: string, options?: any): void; + /** + * The server.decorate('reply', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; +} +/** + * reply.continue([result]) + * Returns control back to the framework without ending the request lifecycle + * [See docs](https://hapijs.com/api/16.1.1#replycontinueresult) + * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) "With the exception of the handler function, all other methods provide the reply.continue() method which instructs the framework to continue processing the request without setting a response." + * @param result if called in the handler, prerequisites, or extension points other than the 'onPreHandler' and 'onPreResponse', the result argument is not allowed and will throw an exception if present. If called within an authentication strategy, it sets the authenticated credentials. If called by the 'onPreHandler' or 'onPreResponse' extensions, the result argument overrides the current response including all headers, and returns control back to the framework to continue processing any remaining extensions. + */ +export interface Continue_Reply { + continue(result?: ReplyValue): Response | undefined; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > authenticate. + * Also [See docs](https://hapijs.com/api/16.1.1#replyerr-result). + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuth extends Base_Reply { + /** + * This function is called if authentication failed. + * TODO, check type the `response` parameter. In https://hapijs.com/api/16.1.1#replyerr-result it is referred to as "null" but this seems to be for a third scenario where it is "used to return both an error and credentials in the authentication methods" then "reply() must be called with three arguments function(err, null, data)" + * @param err any authentication error. + * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. + * @param result an object containing: + * * credentials the authenticated credentials. + * * artifacts optional authentication artifacts. + */ + (err: Error | null, response: AnyAuthenticationResponseAction | null, result: AuthenticationResult): void; + /** + * is called if authentication succeeded + * @param result same object as result above. + */ + continue(result: AuthenticationResult): void; +} +/** + * Typing as any as it's not yet clear what type this argument takes. + * "any authentication response action such as redirection" is it equivalent to + * `ReplyValue` ? + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * TODO research hapi source and type this. + */ +export type AnyAuthenticationResponseAction = any; +/** [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) */ +export interface AuthenticationResult { + credentials?: AuthenticatedCredentials; + artefacts?: any; +} +export interface AuthenticatedCredentials { + // Disabled to allow typing within a project + // [index: string]: any; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > payload + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuthOfPayload extends Base_Reply { + /** + * function called to authenticate the request payload where: + * @param err any authentication error. + * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. + */ + (err: Error | null, response: AnyAuthenticationResponseAction): void; + /** is called if payload authentication succeeded */ + continue(): void; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > response + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuthDecorateResponse extends Base_Reply { + /** + * is called if an error occurred + * @param err any authentication error. + * @param response any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + */ + (err?: Error, response?: ReplyValue): void; + /** is called if the operation succeeded. */ + continue(): void; +} + +export interface ReplyWithContinue extends Continue_Reply, Base_Reply {} + +export interface ReplyNoContinue extends Base_Reply {} + +// TODO assess use and usefulness of StrictReply + +// Concludes the handler activity by setting a response and returning control over to the framework where: +// erran optional error response. +// result an optional response payload. +// Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. +// FLOW CONTROL: +// When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() +/** + * + */ +// export interface Reply { // extends ReplyMethods { +// (err: Error, +// result?: string | number | boolean | Buffer | stream.Stream | Promise | T, +// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ +// credentialData?: any): BoomError; +// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ +// (result: string | number | boolean | Buffer | stream.Stream | Promise | T): Response; +// } + +/** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ +// export interface StrictReply extends ReplyMethods { +// (err: Error, +// result?: Promise | T, +// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ +// credentialData?: any): BoomError; +// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ +// (result: Promise | T): Response; +// } + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Response object + * [See docs](https://hapijs.com/api/16.1.1#response-object) + * + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/16.1.1#response-events) + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ +export interface Response extends Podium { + /** the HTTP response status code. Defaults to 200 (except for errors). */ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. */ + headers: Dictionary; + /** the value provided using the reply interface. */ + source: ReplyValue; + /** + * a string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * * 'promise' - a Promise object. + */ + variety: 'plain' | 'buffer' | 'stream' | 'promise'; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: PluginsStates; + /** response handling flags: */ + settings: { + /** the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. */ + charset: string; + /** the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. */ + encoding: string; + /** if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. */ + passThrough: boolean; + /** options used for source value requiring stringification. Defaults to no replacer and no space padding. */ + stringify: Json.StringifyArguments; + /** if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. */ + ttl: number | null; + /** if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. */ + varyEtag: boolean; + }; + + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + isBoom?: boolean; + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + isMissing?: boolean; + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + output?: Boom.Output; + + /** + * sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) + * @param length the header value. Must match the actual payload size. + */ + bytes(length: number): Response; + /** + * sets the 'Content-Type' HTTP header 'charset' property + * @param charset the charset property value. + */ + charset(charset: string): Response; + /** + * sets the HTTP status code + * @param statusCode the HTTP status code (e.g. 200). + */ + code(statusCode: number): Response; + /** + * sets the HTTP status message + * @param httpMessage the HTTP status message (e.g. 'Ok' for status code 200). + */ + message(httpMessage: string): Response; + /** + * sets the HTTP status code to Created (201) and the HTTP 'Location' header + * @param uri an absolute or relative URI used as the 'Location' header value. + */ + created(uri: string): Response; + /** + * sets the string encoding scheme used to serial data into the HTTP payload + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): Response; + /** + * sets the representation entity tag + * @param tag the entity tag string without the double-quote. + * @param options options object + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true. + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): Response; + /** + * sets an HTTP header + * @param name the header name. + * @param value the header value. + */ + header(name: string, value: string, options?: ResponseHeaderOptionsObject): Response; + /** + * sets the HTTP 'Location' header + * @param uri an absolute or relative URI used as the 'Location' header value. + */ + location(uri: string): Response; + /** + * sets an HTTP redirection response (302) and decorates the response with additional methods listed below, + * @param uri an absolute or relative URI used to redirect the client to another resource. + */ + redirect(uri: string): Response; + /** + * sets the JSON.stringify() replacer argument + * @param method the replacer function or array. Defaults to none. + */ + replacer(method: Json.StringifyReplacer): Response; + /** + * sets the JSON.stringify() space argument + * @param count the number of spaces to indent nested object keys. Defaults to no indentation. + */ + spaces(count: Json.StringifySpace): Response; + /** + * sets an HTTP cookie + * @param name the cookie name. + * @param value the cookie value. If no encoding is defined, must be a string. + * @param options optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). + */ + state(name: string, value: string | Object | any[], options?: ServerStateCookieConfiguationObject): Response; + /** + * sets a string suffix when the response is process via JSON.stringify(). + */ + suffix(suffix: string): Response; + /** + * overrides the default route cache expiration rule for this response instance + * @param msec the time-to-live value in milliseconds. + */ + ttl(msec: number): Response; + /** + * sets the HTTP 'Content-Type' header + * @param mimeType is the mime type. Should only be used to override the built-in default for each response type. + */ + type(mimeType: string): Response; + /** + * clears the HTTP cookie by setting an expired value + * @param name the cookie name. + * @param options optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). + */ + unstate(name: string, options?: ServerStateCookieConfiguationObject): Response; + /** + * adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header + * @param header the HTTP request header name. + */ + vary(header: string): Response; + + /** + * Flow control - hold() + * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: + * puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. + * [See docs](https://hapijs.com/api/16.1.1#flow-control) + */ + hold(): Response; + /** + * Flow control - send() + * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: + * immediately resume the response. Available only after response.hold() is called and until response.send() is invoked once. + * [See docs](https://hapijs.com/api/16.1.1#flow-control) + */ + send(): Response; + + /** + * Mentioned here: "Note that prerequisites do not follow the same rules of the normal reply interface. In all other cases, calling reply() with or without a value will use the result as the response sent back to the client. In a prerequisite method, calling reply() will assign the returned value to the provided assign key. If the returned value is an error, the failAction setting determines the behavior. To force the return value as the response and skip any other prerequisites and the handler, use the reply().takeover() method." + * TODO prepare documentation PR and submit to hapi. + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) + */ + takeover(): Response; +} + +/** + * Response Object Redirect Methods + * When using the redirect() method, the response object provides these additional methods: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + */ +export interface ResponseRedirect extends Response { + /** + * temporary + * sets the status code to 302 or 307 (based on the rewritable() setting) where: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isTemporary if false, sets status to permanent. Defaults to true. + */ + temporary(isTemporary: boolean): Response; + /** + * permanent + * sets the status code to 301 or 308 (based on the rewritable() setting) where: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isPermanent if false, sets status to temporary. Defaults to true. + */ + permanent(isPermanent: boolean): Response; + /** + * rewritable + * sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isRewritable if false, sets to non-rewritable. Defaults to true. + */ + rewritable(isRewritable: boolean): Response; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#response-object) under "response object provides the following methods" > header > options + */ +export interface ResponseHeaderOptionsObject { + /** if true, the value is appended to any existing header value using separator. Defaults to false. */ + append?: boolean; + /** string used as separator when appending to an existing value. Defaults to ','. */ + separator?: string; + /** if false, the header value is not set if an existing value present. Defaults to true. */ + override?: boolean; + /** if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. */ + duplicate?: boolean; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugins and register + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Plugins + * Plugins provide a way to organize the application code by splitting the server logic into smaller components. Each plugin can manipulate the server and its connections through the standard server interface, but with the added ability to sandbox certain properties. + * [See docs](https://hapijs.com/api/16.1.1#plugins) + * @param server the server object the plugin is being registered to. + * @param options an options object passed to the plugin during registration. + * @param next a callback method the function must call to return control back to the framework to complete the registration process with signature function(err) + */ +export interface PluginFunction { + (server: Server, options: OptionsPassedToPlugin, next: (err?: Error) => void): void; + /** + * Note attributes is NOT optional but this type is easier to use. + */ + attributes?: PluginAttributes; +} + +/** + * see Plugin + * [See docs](https://hapijs.com/api/16.1.1#plugins) + */ +export interface PluginAttributes { + /** + * required plugin name string. The name is used as a unique key. Published plugins should use the same name as the name field in the 'package.json' file. Names must be unique within each application. + * NOTE: marked as optional as `pkg` can be used instead. + */ + name?: string; + /** optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. */ + version?: string; + /** Alternatively, the name and version can be included via the pkg attribute containing the 'package.json' file for the module which already has the name and version included */ + pkg?: any; + /** if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + /** optional string or array of string indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: string | string[]; + /** if false, does not allow the plugin to call server APIs that modify the connections such as adding a route or configuring state. This flag allows the plugin to be registered before connections are added and to pass dependency requirements. When set to 'conditional', the mode is based on the presence of selected connections (if the server has connections, it is the same as true, but if no connections are available, it is the same as false). Defaults to true. */ + connections?: boolean | 'conditional'; + /** if true, will only register the plugin once per connection (or once per server for a connectionless plugin). If set, overrides the once option passed to server.register(). Defaults to undefined (registration will be based on the server.register() option once). */ + once?: boolean; +} + +/** + * Plugins State + * Related [See docs](https://hapijs.com/api/16.1.1#serverplugins) + * Related [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ +export interface PluginsStates { + [pluginName: string]: any; +} + +/** + * once, select, routes - optional plugin-specific registration options as defined see PluginRegistrationOptions + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + */ +export interface PluginRegistrationObject extends PluginRegistrationOptions { + /** the plugin registration function. */ + register: PluginFunction; + /** optional options passed to the registration function when called. */ + options?: OptionsPassedToPlugin; +} + +/** + * registration options (different from the options passed to the registration function): + * * once - if true, the registration is skipped for any connection already registered with. Cannot be used with plugin options. If the plugin does not have a connections attribute set to false and the registration selection is empty, registration will be skipped as no connections are available to register once. Defaults to false. + * * routes - modifiers applied to each route added by the plugin: + * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * * select - a string or array of string labels used to pre-select connections for plugin registration. + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + */ +export interface PluginRegistrationOptions { + once?: boolean; + routes?: {prefix?: string, vhost?: string | string[]}; + select?: string | string[]; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JSON + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// This was in a seperate file and perhaps should move to some of the lib typings? +// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16065#issuecomment-299443673 +// +// json/json-tests.ts +// +// import * as JSON from './index'; +// +// var a: JSON.StringifyReplacer = function(key, value) { +// if (key === "do not include") { +// return undefined; +// } +// return value; +// }; +// + +export namespace Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + } } diff --git a/types/hapi/test/connection/table.ts b/types/hapi/test/connection/table.ts new file mode 100644 index 0000000000..dee4741b07 --- /dev/null +++ b/types/hapi/test/connection/table.ts @@ -0,0 +1,20 @@ + +// From https://hapijs.com/api/16.1.1#servertablehost + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80, host: 'example.com' }); +server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + +const connection = server.connections[0]; +const table = connection.table(); + +/* + [ + { + method: 'get', + path: '/example', + settings: { ... } + } + ] +*/ diff --git a/types/hapi/test/getting-started/01-creating-a-server.ts b/types/hapi/test/getting-started/01-creating-a-server.ts new file mode 100644 index 0000000000..819ab5108e --- /dev/null +++ b/types/hapi/test/getting-started/01-creating-a-server.ts @@ -0,0 +1,16 @@ +// From https://hapijs.com/tutorials/getting-started#creating-a-server + +'use strict'; + +import Hapi = require('hapi'); + +const server = new Hapi.Server(); +server.connection({ port: 3000, host: 'localhost' }); + +server.start((err) => { + + if (err) { + throw err; + } + console.log(`Server running at: ${server.info!.uri}`); +}); diff --git a/types/hapi/test/getting-started/02-adding-routes.ts b/types/hapi/test/getting-started/02-adding-routes.ts new file mode 100644 index 0000000000..db4805366c --- /dev/null +++ b/types/hapi/test/getting-started/02-adding-routes.ts @@ -0,0 +1,32 @@ +// from https://hapijs.com/tutorials/getting-started#adding-routes + +'use strict'; + +import Hapi = require('hapi'); + +const server = new Hapi.Server(); +server.connection({ port: 3000, host: 'localhost' }); + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + reply('Hello, world!'); + } +}); + +server.route({ + method: 'GET', + path: '/{name}', + handler: function (request, reply) { + reply('Hello, ' + encodeURIComponent(request.params.name) + '!'); + } +}); + +server.start((err) => { + + if (err) { + throw err; + } + console.log(`Server running at: ${server.info!.uri}`); +}); diff --git a/types/hapi/test/getting-started/03-serving-static-content.ts b/types/hapi/test/getting-started/03-serving-static-content.ts new file mode 100644 index 0000000000..06200f2b07 --- /dev/null +++ b/types/hapi/test/getting-started/03-serving-static-content.ts @@ -0,0 +1,23 @@ +'use strict'; + +import Hapi = require('hapi'); +import Inert = require('inert'); + +const server = new Hapi.Server(); + +// from https://hapijs.com/tutorials/getting-started#creating-static-pages-and-content + +server.register(Inert, (err) => { + + if (err) { + throw err; + } + + server.route({ + method: 'GET', + path: '/hello', + handler: function (request, reply) { + reply.file('./public/hello.html'); + } + }); +}); \ No newline at end of file diff --git a/types/hapi/test/getting-started/04-using-plugins.ts b/types/hapi/test/getting-started/04-using-plugins.ts new file mode 100644 index 0000000000..28d1a1b576 --- /dev/null +++ b/types/hapi/test/getting-started/04-using-plugins.ts @@ -0,0 +1,56 @@ +// from https://hapijs.com/tutorials/getting-started#using-plugins + +'use strict'; + +import Hapi = require('hapi'); +const Good = require('good'); + +const server = new Hapi.Server(); +server.connection({ port: 3000, host: 'localhost' }); + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + reply('Hello, world!'); + } +}); + +server.route({ + method: 'GET', + path: '/{name}', + handler: function (request, reply) { + reply('Hello, ' + encodeURIComponent(request.params.name) + '!'); + } +}); + +server.register({ + register: Good, + options: { + reporters: { + console: [{ + module: 'good-squeeze', + name: 'Squeeze', + args: [{ + response: '*', + log: '*' + }] + }, { + module: 'good-console' + }, 'stdout'] + } + } +}, (err) => { + + if (err) { + throw err; // something bad happened loading the plugin + } + + server.start((err) => { + + if (err) { + throw err; + } + server.log('info', 'Server running at: ' + server.info!.uri); + }); +}); diff --git a/types/hapi/test/path/catch-all.ts b/types/hapi/test/path/catch-all.ts new file mode 100644 index 0000000000..c9002392b1 --- /dev/null +++ b/types/hapi/test/path/catch-all.ts @@ -0,0 +1,15 @@ + +// From https://hapijs.com/api/16.1.1#catch-all-route + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.route({ + method: '*', + path: '/{p*}', + handler: function (request, reply) { + + return reply('The page was not found').code(404); + } +}); diff --git a/types/hapi/test/path/parameters.ts b/types/hapi/test/path/parameters.ts new file mode 100644 index 0000000000..62bbfcc638 --- /dev/null +++ b/types/hapi/test/path/parameters.ts @@ -0,0 +1,33 @@ + +// From https://hapijs.com/api/16.1.1#path-parameters + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const getAlbum: Hapi.RouteHandler = function (request, reply) { + + return reply('You asked for ' + + (request.params.song ? request.params.song + ' from ' : '') + + request.params.album); +}; + +server.route({ + path: '/{album}/{song?}', + method: 'GET', + handler: getAlbum +}); + +// Example 2 + +const getPerson: Hapi.RouteHandler = function (request, reply) { + + const nameParts = request.params.name.split('/'); + return reply({ first: nameParts[0], last: nameParts[1] }); +}; + +server.route({ + path: '/person/{name*2}', // Matches '/person/john/doe' + method: 'GET', + handler: getPerson +}); diff --git a/types/hapi/test/plugins/options.ts b/types/hapi/test/plugins/options.ts new file mode 100644 index 0000000000..cd192f1996 --- /dev/null +++ b/types/hapi/test/plugins/options.ts @@ -0,0 +1,36 @@ + +// From https://hapijs.com/api/16.1.1#serverinfo + +import * as Hapi from 'hapi'; + +// added in addition to code from docs +interface PluginOptions { + quantity: number; +} + +// modified from docs +var registerFunction: Hapi.PluginFunction = function(server, options, next) { + + server.route({ + method: 'GET', + path: '/test', + handler: function (request, reply) { + + // modified from docs + return reply(`ok ${options.quantity}`); + } + }); + + return next(); +}; + +var attributes: Hapi.PluginAttributes = { + name: 'test', + version: '1.0.0' +}; + +var attributes: Hapi.PluginAttributes = { + pkg: {} // require('./package.json'), +}; + +registerFunction.attributes = attributes; diff --git a/types/hapi/test/reply/continue.ts b/types/hapi/test/reply/continue.ts new file mode 100644 index 0000000000..de6994fbd0 --- /dev/null +++ b/types/hapi/test/reply/continue.ts @@ -0,0 +1,15 @@ + +// From https://hapijs.com/api/16.1.1#replycontinueresult + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); +}; + +server.ext('onRequest', onRequest); diff --git a/types/hapi/test/reply/entity.ts b/types/hapi/test/reply/entity.ts new file mode 100644 index 0000000000..cfcce6de25 --- /dev/null +++ b/types/hapi/test/reply/entity.ts @@ -0,0 +1,24 @@ + +// From https://hapijs.com/api/16.1.1#replyentityoptions + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.route({ + method: 'GET', + path: '/', + config: { + cache: { expiresIn: 5000 }, + handler: function (request, reply) { + + const response = reply.entity({ etag: 'abc' }); + if (response) { + response.header('X', 'y'); + return; + } + + return reply('ok'); + } + } +}); diff --git a/types/hapi/test/reply/redirect.ts b/types/hapi/test/reply/redirect.ts new file mode 100644 index 0000000000..5baf892ac1 --- /dev/null +++ b/types/hapi/test/reply/redirect.ts @@ -0,0 +1,8 @@ + +// From https://hapijs.com/api/16.1.1#replyredirecturi + +import * as Hapi from 'hapi'; +const handler: Hapi.RouteHandler = function (request, reply) { + + return reply.redirect('http://example.com'); +}; diff --git a/types/hapi/test/reply/reply.ts b/types/hapi/test/reply/reply.ts new file mode 100644 index 0000000000..31f3bff9b4 --- /dev/null +++ b/types/hapi/test/reply/reply.ts @@ -0,0 +1,22 @@ + +// From https://hapijs.com/api/16.1.1#replyerr-result + +import * as Hapi from 'hapi'; + +// verbose notation + +const handler: Hapi.RouteHandler = function (request, reply) { + + const response = reply('success'); + response.type('text/plain'); + response.header('X-Custom', 'some-value'); +}; + +// Chained notation + +const handler2: Hapi.RouteHandler = function (request, reply) { + + return reply('success') + .type('text/plain') + .header('X-Custom', 'some-value'); +}; \ No newline at end of file diff --git a/types/hapi/test/reply/state_cookie.ts b/types/hapi/test/reply/state_cookie.ts new file mode 100644 index 0000000000..bf94219311 --- /dev/null +++ b/types/hapi/test/reply/state_cookie.ts @@ -0,0 +1,33 @@ + +// from https://hapijs.com/tutorials/cookies?lang=en_US + +import * as Hapi from 'hapi'; + +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.state('data', { + ttl: null, + isSecure: true, + isHttpOnly: true, + encoding: 'base64json', + clearInvalid: false, // remove invalid cookies + strictHeader: true // don't allow violations of RFC 6265 +}); + +server.route({ + method: 'GET', + path: '/say-hello', + config: { + state: { + parse: true, // parse and store in request.state + failAction: 'error' // may also be 'ignore' or 'log' + } + }, + handler: function(request, reply) { + // TODO test this + reply('Hello').state('data', { firstVisit: false }); + } +}) + + diff --git a/types/hapi/test/request/event-types.ts b/types/hapi/test/request/event-types.ts new file mode 100644 index 0000000000..0946f0a0ed --- /dev/null +++ b/types/hapi/test/request/event-types.ts @@ -0,0 +1,30 @@ + +// From https://hapijs.com/api/16.1.1#requestsetmethodmethod + +import * as Hapi from 'hapi'; +const Crypto = require('crypto'); +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { + + const hash = Crypto.createHash('sha1'); + request.on('peek', (chunk) => { + + hash.update(chunk); + }); + + request.once('finish', () => { + + console.log(hash.digest('hex')); + }); + + request.once('disconnect', () => { + + console.error('request aborted'); + }); + + return reply.continue(); +}; + +server.ext('onRequest', onRequest); diff --git a/types/hapi/test/request/generate-response.ts b/types/hapi/test/request/generate-response.ts new file mode 100644 index 0000000000..c30c3a7be5 --- /dev/null +++ b/types/hapi/test/request/generate-response.ts @@ -0,0 +1,21 @@ + +// From https://hapijs.com/api/16.1.1#requestgenerateresponsesource-options + +import * as Hapi from 'hapi'; + +// Added in addition to code from docs +function promiseMethod() { + return Promise.resolve(true); +} + +const handler: Hapi.ServerExtRequestHandler = function (request, reply) { + + const result = promiseMethod().then((thing: boolean) => { + + if (!thing) { + return request.generateResponse().code(214); + } + return thing; + }); + return reply(result); +}; diff --git a/types/hapi/test/request/get-log.ts b/types/hapi/test/request/get-log.ts new file mode 100644 index 0000000000..289bdd3282 --- /dev/null +++ b/types/hapi/test/request/get-log.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#requestgetlogtags-internal + +import * as Hapi from 'hapi'; + +var request: Hapi.Request = {}; + +request.getLog(); +request.getLog('error'); +request.getLog(['error', 'auth']); +request.getLog(['error'], true); +request.getLog(false); diff --git a/types/hapi/test/request/log.ts b/types/hapi/test/request/log.ts new file mode 100644 index 0000000000..1c2da1f3b0 --- /dev/null +++ b/types/hapi/test/request/log.ts @@ -0,0 +1,19 @@ + +// From https://hapijs.com/api/16.1.1#requestlogtags-data-timestamp + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80, routes: { log: true, security: false } }); + +server.on('request', (request, event, tags) => { + + if (tags.error) { + console.log(event); + } +}); + +const handler: Hapi.RouteHandler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); +}; diff --git a/types/hapi/test/request/set-method.ts b/types/hapi/test/request/set-method.ts new file mode 100644 index 0000000000..7269e6255f --- /dev/null +++ b/types/hapi/test/request/set-method.ts @@ -0,0 +1,15 @@ + +// From https://hapijs.com/api/16.1.1#requestsetmethodmethod + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); +}; + +server.ext('onRequest', onRequest); diff --git a/types/hapi/test/request/set-url.ts b/types/hapi/test/request/set-url.ts new file mode 100644 index 0000000000..4add3c5a17 --- /dev/null +++ b/types/hapi/test/request/set-url.ts @@ -0,0 +1,32 @@ + +// From https://hapijs.com/api/16.1.1#requestseturlurl-striptrailingslash + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +var onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); +}; + +server.ext('onRequest', onRequest); + +// Example 2 + +const Url = require('url'); +const Qs = require('qs'); + +onRequest = function (request, reply) { + + const uri = request.raw.req.url; + const parsed = Url.parse(uri, false); + parsed.query = Qs.parse(parsed.query); + request.setUrl(parsed); + + return reply.continue(); +}; + +server.ext('onRequest', onRequest); diff --git a/types/hapi/test/request/tail.ts b/types/hapi/test/request/tail.ts new file mode 100644 index 0000000000..9c68ccb8f2 --- /dev/null +++ b/types/hapi/test/request/tail.ts @@ -0,0 +1,26 @@ + +// From https://hapijs.com/api/16.1.1#requestsetmethodmethod + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const get: Hapi.RouteHandler = function (request, reply) { + + const dbTail = request.tail('write to database'); + + var db: any; + db.save('key', 'value', () => { + + dbTail(); + }); + + return reply('Success!'); +}; + +server.route({ method: 'GET', path: '/', handler: get }); + +server.on('tail', (request) => { + + console.log('Request completed including db activity'); +}); diff --git a/types/hapi/test/response/error-representation.ts b/types/hapi/test/response/error-representation.ts new file mode 100644 index 0000000000..f0fb62eb30 --- /dev/null +++ b/types/hapi/test/response/error-representation.ts @@ -0,0 +1,33 @@ + +// From https://hapijs.com/api/16.1.1#error-transformation + +import * as Hapi from 'hapi'; +import Vision from 'vision'; +const server = new Hapi.Server(); +server.register(Vision, {}, (err) => { + server.views({ + engines: { + html: require('handlebars') + } + }); +}); +server.connection({ port: 80 }); + +const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { + + const response = request.response!; + if (!response.isBoom) { + return reply.continue(); + } + + // Replace error with friendly HTML + + const error = response; + const ctx = { + message: (error.output!.statusCode === 404 ? 'page not found' : 'something went wrong') + }; + + return reply.view('error', ctx); +}; + +server.ext('onPreResponse', preResponse); diff --git a/types/hapi/test/response/error.ts b/types/hapi/test/response/error.ts new file mode 100644 index 0000000000..0ef503df12 --- /dev/null +++ b/types/hapi/test/response/error.ts @@ -0,0 +1,25 @@ + +// From https://hapijs.com/api/16.1.1#error-response + +import * as Hapi from 'hapi'; +const Boom = require('boom'); + +const server = new Hapi.Server(); + +server.route({ + method: 'GET', + path: '/badRequest', + handler: function (request, reply) { + + return reply(Boom.badRequest('Unsupported parameter')); + } +}); + +server.route({ + method: 'GET', + path: '/internal', + handler: function (request, reply) { + + return reply(new Error('unexpect error')); + } +}); diff --git a/types/hapi/test/response/events.ts b/types/hapi/test/response/events.ts new file mode 100644 index 0000000000..2d1658087b --- /dev/null +++ b/types/hapi/test/response/events.ts @@ -0,0 +1,30 @@ + +// From https://hapijs.com/api/16.1.1#response-events + +import * as Hapi from 'hapi'; +const Crypto = require('crypto'); +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { + + const response = request.response!; + if (response.isBoom) { + return reply(); + } + + const hash = Crypto.createHash('sha1'); + response.on('peek', (chunk) => { + + hash.update(chunk); + }); + + response.once('finish', () => { + + console.log(hash.digest('hex')); + }); + + return reply.continue(); +}; + +server.ext('onPreResponse', preResponse); diff --git a/types/hapi/test/response/flow-control.ts b/types/hapi/test/response/flow-control.ts new file mode 100644 index 0000000000..bc18a36aff --- /dev/null +++ b/types/hapi/test/response/flow-control.ts @@ -0,0 +1,14 @@ + +// From https://hapijs.com/api/16.1.1#flow-control + +import * as Hapi from 'hapi'; + +const handler = function (request: Hapi.Request, reply: Hapi.ReplyWithContinue) { + + const response = reply('success').hold(); + + setTimeout(() => { + + response.send(); + }, 1000); +}; diff --git a/types/hapi/test/route/additional-options.ts b/types/hapi/test/route/additional-options.ts new file mode 100644 index 0000000000..99e818d08a --- /dev/null +++ b/types/hapi/test/route/additional-options.ts @@ -0,0 +1,39 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +var authConfig: Hapi.RouteAdditionalConfigurationOptions = { + app: {} +}; + +// Handler in config +const user: Hapi.RouteAdditionalConfigurationOptions = { + cache: { expiresIn: 5000, statuses: [200, 201] }, + handler: function (request, reply) { + + return reply({ name: 'John' }); + } +}; + +// Add in addition to examples in docs + +var cache: Hapi.RouteCacheOptions = { + privacy: 'default', + expiresIn: 5000, +}; + +cache = { + privacy: 'default', + expiresAt: '22:44', +}; + +cache = { + privacy: 'default', +}; + +/* should error (as does!) +var cache: Hapi.RouteCacheOptions = { + expiresIn: 5000, + expiresAt: '22:44', +}; +*/ diff --git a/types/hapi/test/route/auth.ts b/types/hapi/test/route/auth.ts new file mode 100644 index 0000000000..e5239322da --- /dev/null +++ b/types/hapi/test/route/auth.ts @@ -0,0 +1,25 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +var routeMoreConfig: Hapi.RouteAdditionalConfigurationOptions = { + auth: false, +} +routeMoreConfig = { + auth: 'some_strategy', +} +routeMoreConfig = { + auth: { + mode: 'required', + strategies: ['strat1', 'strat2'], + strategy: 'should not be given when strategies given', + payload: false, + access: { + scope: false, + entity: 'any', + }, + // Will over write values in access + scope: false, + entity: 'any', + } +} diff --git a/types/hapi/test/route/config.ts b/types/hapi/test/route/config.ts new file mode 100644 index 0000000000..16457395f8 --- /dev/null +++ b/types/hapi/test/route/config.ts @@ -0,0 +1,46 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +// different methods +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + vhost: 'site.coms', +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: '*' +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: ['OPTIONS', '*'] +}; + +// different handlers +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + handler: 'some registered handler' +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + handler: function (request, reply) { + return reply('ok'); + } +}; + +const server = new Hapi.Server(); +server.route(routeConfig); + +// Handler in config +const user: Hapi.RouteAdditionalConfigurationOptions = { + cache: { expiresIn: 5000 }, + handler: function (request, reply) { + + return reply({ name: 'John' }); + } +}; + +server.route({method: 'GET', path: '/user', config: user }); diff --git a/types/hapi/test/route/handler.ts b/types/hapi/test/route/handler.ts new file mode 100644 index 0000000000..c66d17018e --- /dev/null +++ b/types/hapi/test/route/handler.ts @@ -0,0 +1,10 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +var handler: Hapi.RouteHandler = function(request, reply) { + reply('success'); +} +var strictHandler: Hapi.RouteHandler = function(request, reply) { + reply(123); +} diff --git a/types/hapi/test/route/prerequisites.ts b/types/hapi/test/route/prerequisites.ts new file mode 100644 index 0000000000..c4ca7650fa --- /dev/null +++ b/types/hapi/test/route/prerequisites.ts @@ -0,0 +1,47 @@ + +// From https://hapijs.com/api/16.1.1#route-prerequisites + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const pre1: Hapi.RoutePrerequisiteRequestHandler = function (request, reply) { + + return reply('Hello'); +}; + +const pre2: Hapi.RoutePrerequisiteRequestHandler = function (request, reply) { + + return reply('World'); +}; + +const pre3: Hapi.RoutePrerequisiteRequestHandler = function (request, reply) { + const pre = request.pre as Pre1; + return reply(pre.m1 + ' ' + pre.m2); +}; + +server.route({ + method: 'GET', + path: '/', + config: { + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + handler: function (request, reply) { + const pre = request.pre as Pre2; + return reply(pre.m3 + '\n'); + } + } +}); +interface Pre1 { + m1: string; + m2: string; +} +interface Pre2 extends Pre1 { + m3: string; +} diff --git a/types/hapi/test/route/public-interface.ts b/types/hapi/test/route/public-interface.ts new file mode 100644 index 0000000000..e61fb8275f --- /dev/null +++ b/types/hapi/test/route/public-interface.ts @@ -0,0 +1,17 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +var route = {}; + +var a: string = route.method; +var a: string = route.path; +if (typeof(route.vhost) == 'string') { + var a: string = route.vhost; +} else { + var b: string[] = route.vhost!; +} +var c: Hapi.ServerRealm = route.realm; +var d: Hapi.RouteAdditionalConfigurationOptions = route.settings; +var a: string = route.fingerprint; +var e: boolean = route.auth.access( {}); diff --git a/types/hapi/test/server/app.ts b/types/hapi/test/server/app.ts new file mode 100644 index 0000000000..dac8921c20 --- /dev/null +++ b/types/hapi/test/server/app.ts @@ -0,0 +1,11 @@ + +// From https://hapijs.com/api/16.1.1#serverapp + +import * as Hapi from 'hapi'; +var server = new Hapi.Server(); +server.app.key = 'value'; + +const handler: Hapi.RouteHandler = function (request, reply) { + + return reply(request.server.app.key); +}; diff --git a/types/hapi/test/server/auth.ts b/types/hapi/test/server/auth.ts new file mode 100644 index 0000000000..3f28732d42 --- /dev/null +++ b/types/hapi/test/server/auth.ts @@ -0,0 +1,101 @@ + +// From https://hapijs.com/api/16.1.1#serverauthapi + +import * as Hapi from 'hapi'; +import * as Boom from 'boom'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +var scheme: Hapi.ServerAuthScheme = function (server, options) { + + return { + api: { + settings: { + x: 5 + } + }, + authenticate: function (request, reply) { + + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + + return reply.continue({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +console.log(server.auth.api.default.settings.x); // 5 + +// Default + +server.auth.default('default'); + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + + return reply(request.auth.credentials.user); + } +}); + +// scheme + +scheme = function (server, options) { + + return { + authenticate: function (request, reply) { + + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + + return reply.continue({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); + +// strategy + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + handler: function (request, reply) { + + return reply(request.auth.credentials.user); + } + } +}); + +// test + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + + request.server.auth.test('default', request, (err, credentials) => { + + if (err) { + return reply({ status: false }); + } + + return reply({ status: true, user: (credentials as any).name }); + }); + } +}); diff --git a/types/hapi/test/server/bind.ts b/types/hapi/test/server/bind.ts new file mode 100644 index 0000000000..2741e16c82 --- /dev/null +++ b/types/hapi/test/server/bind.ts @@ -0,0 +1,24 @@ + +// From https://hapijs.com/api/16.1.1#serverbindcontext + +import * as Hapi from 'hapi'; + +interface HandlerThis { + message: string; +} + +const handler: Hapi.RouteHandler = function (this: HandlerThis, request, reply) { + + return reply(this.message); +}; + +var register: Hapi.PluginFunction<{}> = function (server, options, next) { + + const bind: HandlerThis = { + message: 'hello' + }; + + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); +}; diff --git a/types/hapi/test/server/cache.ts b/types/hapi/test/server/cache.ts new file mode 100644 index 0000000000..4cb9eaa4b7 --- /dev/null +++ b/types/hapi/test/server/cache.ts @@ -0,0 +1,33 @@ + +// From https://hapijs.com/api/16.1.1#servercacheoptions + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); +cache.set('norway', { capital: 'oslo' }, null, (err) => { + + cache.get('norway', (err, value, cached, log) => { + + // value === { capital: 'oslo' }; + }); +}); + +// provision +// From https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback + +server.initialize((err) => { + + server.cache.provision({ engine: require('catbox-memory'), name: 'countries' }, (err) => { + + const cache = server.cache({ cache: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, (err) => { + + cache.get('norway', (err, value, cached, log) => { + + // value === { capital: 'oslo' }; + }); + }); + }); +}); diff --git a/types/hapi/test/server/connection-options.ts b/types/hapi/test/server/connection-options.ts new file mode 100644 index 0000000000..3a526307db --- /dev/null +++ b/types/hapi/test/server/connection-options.ts @@ -0,0 +1,39 @@ + +// From https://hapijs.com/api/16.1.1#serverconnectionoptions + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); + +const web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); +const admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + +server.connections.length === 2; +web.connections.length === 1; +admin.connections.length === 1; + +// example 2 + +var registerFunction: Hapi.PluginFunction<{}> = function (srv, options, next) { + + // Use the 'srv' argument to add a new connection + + const server = srv.connection(); + + // Use the 'server' return value to manage the new connection + + server.route({ + path: '/', + method: 'GET', + handler: function (request, reply) { + + return reply('hello'); + } + }); + + return next(); +}; + +registerFunction.attributes = { + name: 'example', + connections: false +}; diff --git a/types/hapi/test/server/connections.ts b/types/hapi/test/server/connections.ts new file mode 100644 index 0000000000..fb2f9f303e --- /dev/null +++ b/types/hapi/test/server/connections.ts @@ -0,0 +1,13 @@ + +// From https://hapijs.com/api/16.1.1#serverconnections + +import * as Hapi from 'hapi'; +var server = new Hapi.Server(); +server.connection({ port: 80, labels: 'a' }); +server.connection({ port: 8080, labels: 'b' }); + +// server.connections.length === 2 + +const a = server.select('a'); + +// a.connections.length === 1 diff --git a/types/hapi/test/server/decoder.ts b/types/hapi/test/server/decoder.ts new file mode 100644 index 0000000000..edd52485ea --- /dev/null +++ b/types/hapi/test/server/decoder.ts @@ -0,0 +1,9 @@ + +// From https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder + +import * as Hapi from 'hapi'; +import * as Zlib from 'zlib'; +const server = new Hapi.Server(); +server.connection({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); + +server.decoder('special', (options) => Zlib.createGunzip(options)); diff --git a/types/hapi/test/server/decorate.ts b/types/hapi/test/server/decorate.ts new file mode 100644 index 0000000000..540e29c951 --- /dev/null +++ b/types/hapi/test/server/decorate.ts @@ -0,0 +1,68 @@ + +// From https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const success = function (this: Hapi.ReplyNoContinue) { + + return this.response({ status: 'ok' }); +}; + +server.decorate('reply', 'success', success); + +declare module 'hapi' { + interface Base_Reply { + success: () => Response; + } +} + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + + return reply.success(); + } +}); + +// custom typing code for decorating request + +server.decorate('request', 'some_request_method', (request) => { + return function() { + // Do some sort of processing; + return request.id; + } +}, {apply: true}); + +declare module 'hapi' { + interface Request { + some_request_method(): void; + } +} + +server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.some_request_method(); + return reply(); + } +}); + +// custom typing code for decorating server + +server.decorate('server', 'some_server_method', (server: Hapi.Server) => { + return function(arg1: number){ + return "some text"; + } +}); + +declare module 'hapi' { + interface Server { + some_server_method(arg1: number): string; + } +} + +server.some_server_method(1); diff --git a/types/hapi/test/server/dependency.ts b/types/hapi/test/server/dependency.ts new file mode 100644 index 0000000000..1d63397cf2 --- /dev/null +++ b/types/hapi/test/server/dependency.ts @@ -0,0 +1,24 @@ + +// From https://hapijs.com/api/16.1.1#serverdependencydependencies-after + +import * as Hapi from 'hapi'; + +const after: Hapi.AfterDependencyLoadCallback = function (server, next) { + + // Additional plugin registration logic + return next(); +}; + +var registerFunction: Hapi.PluginFunction<{}> = function (server, options, next) { + + server.dependency('yar', after); + return next(); +}; + +// Example 2, via attributes + +registerFunction.attributes = { + name: 'test', + version: '1.0.0', + dependencies: 'yar' +}; diff --git a/types/hapi/test/server/emit.ts b/types/hapi/test/server/emit.ts new file mode 100644 index 0000000000..d248f7d4ab --- /dev/null +++ b/types/hapi/test/server/emit.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#serveremitcriteria-data-callback + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.event('test'); +server.on('test', (update: Update) => console.log(update)); +type Update = string; +var toSend: Update = 'hello'; +server.emit('test', toSend); diff --git a/types/hapi/test/server/encoder.ts b/types/hapi/test/server/encoder.ts new file mode 100644 index 0000000000..f35102b776 --- /dev/null +++ b/types/hapi/test/server/encoder.ts @@ -0,0 +1,9 @@ + +// From https://hapijs.com/api/16.1.1#serverencoderencoding-encoder + +import * as Hapi from 'hapi'; +import * as Zlib from 'zlib'; +const server = new Hapi.Server(); +server.connection({ port: 80, routes: { compression: { special: { chunkSize: 16 * 1024 } } } }); + +server.encoder('special', (options) => Zlib.createGzip(options)); diff --git a/types/hapi/test/server/event.ts b/types/hapi/test/server/event.ts new file mode 100644 index 0000000000..f0c2215f12 --- /dev/null +++ b/types/hapi/test/server/event.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#servereventevents + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.event('test'); +server.on('test', (update: Update) => console.log(update)); +type Update = string; +var toSend: Update = 'hello'; +server.emit('test', toSend); diff --git a/types/hapi/test/server/expose.ts b/types/hapi/test/server/expose.ts new file mode 100644 index 0000000000..effbc1ae49 --- /dev/null +++ b/types/hapi/test/server/expose.ts @@ -0,0 +1,17 @@ + +// From https://hapijs.com/api/16.1.1#serverexposekey-value + +import * as Hapi from 'hapi'; +var register: Hapi.PluginFunction<{}> = function (server, options, next) { + + server.expose('util', function () { console.log('something'); }); + return next(); +}; + +// example of `expose()` merging object + +register = function (server, options, next) { + + server.expose({ util: function () { console.log('something'); } }); + return next(); +}; diff --git a/types/hapi/test/server/ext.ts b/types/hapi/test/server/ext.ts new file mode 100644 index 0000000000..410c913c41 --- /dev/null +++ b/types/hapi/test/server/ext.ts @@ -0,0 +1,46 @@ + +// From https://hapijs.com/api/16.1.1#serverextevents + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.ext({ + type: 'onRequest', + method: function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + } +}); + +var handler: Hapi.RouteHandler = function (request, reply) { + + return reply({ status: 'ok' }); +}; + +server.route({ method: 'GET', path: '/test', handler: handler }); +server.start((err) => { }); + +// All requests will get routed to '/test' + + +// Example 2 + +server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); +}); + +handler = function (request, reply) { + + return reply({ status: 'ok' }); +}; + +server.route({ method: 'GET', path: '/test', handler: handler }); +server.start((err) => { }); + +// All requests will get routed to '/test' diff --git a/types/hapi/test/server/handler.ts b/types/hapi/test/server/handler.ts new file mode 100644 index 0000000000..713fe7f114 --- /dev/null +++ b/types/hapi/test/server/handler.ts @@ -0,0 +1,55 @@ + +// From https://hapijs.com/api/16.1.1#serverhandlername-method + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ host: 'localhost', port: 8000 }); + +// Defines new handler for routes on this server +var handler: Hapi.MakeRouteHandler = function (route, options) { + + return function (request, reply) { + + return reply('new handler: ' + options.msg); + } +}; + +server.handler('test', handler); + +interface TestPluginConfig { + msg: string; +} + +declare module 'hapi' { + interface RouteHandlerPlugins { + test?: TestPluginConfig; + } +} + +server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } +}); + +server.start(function (err) { }); + +// example 2 + +handler = function (route, options: TestPluginConfig) { + + return function (request, reply) { + + return reply('new handler: ' + options.msg); + } +}; + +// Change the default payload processing for this handler +handler.defaults = { + payload: { + output: 'stream', + parse: false + } +}; + +server.handler('test', handler); diff --git a/types/hapi/test/server/info.ts b/types/hapi/test/server/info.ts new file mode 100644 index 0000000000..eaf1b39747 --- /dev/null +++ b/types/hapi/test/server/info.ts @@ -0,0 +1,16 @@ + +// From https://hapijs.com/api/16.1.1#serverinfo + +import assert = require('assert'); +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +var options: Hapi.ServerConnectionOptions = { port: 80 }; +server.connection(options); + +if(server.info) assert(server.info.port === 80); + +options = { port: 8080 }; +server.connection(options); + +assert(server.info === null); +assert(server.connections[1].info.port === 8080); diff --git a/types/hapi/test/server/initialize.ts b/types/hapi/test/server/initialize.ts new file mode 100644 index 0000000000..7ef4b51527 --- /dev/null +++ b/types/hapi/test/server/initialize.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#serverinitializecallback + +import * as Hapi from 'hapi'; +const Hoek = require('hoek'); +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.initialize((err) => { + + Hoek.assert(!err, err); +}); diff --git a/types/hapi/test/server/inject.ts b/types/hapi/test/server/inject.ts new file mode 100644 index 0000000000..130af7489b --- /dev/null +++ b/types/hapi/test/server/inject.ts @@ -0,0 +1,18 @@ + +// From https://hapijs.com/api/16.1.1#serverinjectoptions-callback + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const handler: Hapi.RouteHandler = function (request, reply) { + + return reply('Success!'); +}; + +server.route({ method: 'GET', path: '/', handler: handler }); + +server.inject('/', (res) => { + + console.log(res.result); +}); diff --git a/types/hapi/test/server/listener.ts b/types/hapi/test/server/listener.ts new file mode 100644 index 0000000000..d7bb6fc5ea --- /dev/null +++ b/types/hapi/test/server/listener.ts @@ -0,0 +1,19 @@ + +// From https://hapijs.com/api/16.1.1#serverlistener + +import * as Hapi from 'hapi'; +import SocketIO = require('socket.io'); + +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +// https://socket.io/docs/server-api/#server-attach-httpserver-options +const io = SocketIO.listen(server.listener); +io.sockets.on('connection', (socket) => { + + // TODO, FIXME by removing , probably `socket` type given here is + // a wrapper around socket.io. Much less likely is either + // a type error in the TypeScript definitions of socket.io or + // an error in the Hapi docs. + socket.emit( { msg: 'welcome' }); +}); diff --git a/types/hapi/test/server/load.ts b/types/hapi/test/server/load.ts new file mode 100644 index 0000000000..ee204c864f --- /dev/null +++ b/types/hapi/test/server/load.ts @@ -0,0 +1,7 @@ + +// From https://hapijs.com/api/16.1.1#serverload + +import * as Hapi from 'hapi'; +const server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + +var d: number = server.load.rss; diff --git a/types/hapi/test/server/log.ts b/types/hapi/test/server/log.ts new file mode 100644 index 0000000000..4507358d60 --- /dev/null +++ b/types/hapi/test/server/log.ts @@ -0,0 +1,15 @@ + +// From https://hapijs.com/api/16.1.1#serverlogtags-data-timestamp + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.on('log', (event, tags) => { + + if (tags.error) { + console.log(event); + } +}); + +server.log(['test', 'error'], 'Test event'); diff --git a/types/hapi/test/server/lookup.ts b/types/hapi/test/server/lookup.ts new file mode 100644 index 0000000000..89ce852700 --- /dev/null +++ b/types/hapi/test/server/lookup.ts @@ -0,0 +1,19 @@ + +// From https://hapijs.com/api/16.1.1#serverlookupid + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection(); +server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { + + return reply(); + }, + id: 'root' + } +}); + +const route = server.lookup('root'); diff --git a/types/hapi/test/server/match.ts b/types/hapi/test/server/match.ts new file mode 100644 index 0000000000..f322a31494 --- /dev/null +++ b/types/hapi/test/server/match.ts @@ -0,0 +1,19 @@ + +// From https://hapijs.com/api/16.1.1#servermatchmethod-path-host + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection(); +server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { + + return reply(); + }, + id: 'root' + } +}); + +const route = server.match('get', '/'); diff --git a/types/hapi/test/server/method.ts b/types/hapi/test/server/method.ts new file mode 100644 index 0000000000..a67022d250 --- /dev/null +++ b/types/hapi/test/server/method.ts @@ -0,0 +1,78 @@ + +// From https://hapijs.com/api/16.1.1#servermethodname-method-options + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +// Simple arguments + +const add = function (a: number, b: number, next: Hapi.ServerMethodNext) { + + return next(null, a + b); +}; + +server.method('sum', add, { cache: { expiresIn: 2000, generateTimeout: 100 } }); + +var next: Hapi.ServerMethodNext = (err, result) => { + + console.log(result); +}; +server.methods.sum(4, 5, next); + +// Object argument + +const addArray = function (array: number[], next: Hapi.ServerMethodNext) { + + let sum = 0; + array.forEach((item) => { + + sum += item; + }); + + return next(null, sum); +}; + +server.method('sumObj', addArray, { + cache: { expiresIn: 2000, generateTimeout: 100 }, + generateKey: function (array) { + + return array.join(','); + } +}); + +var next: Hapi.ServerMethodNext = (err, result) => { + + console.log(result); +}; +server.methods.sumObj([5, 6], next); + +// Synchronous method with cache + +const addSync = function (a: number, b: number) { + + return a + b; +}; + +server.method('sumSync', addSync, { cache: { expiresIn: 2000, generateTimeout: 100 }, callback: false }); + +var next: Hapi.ServerMethodNext = (err, result) => { + + console.log(result); +}; +server.methods.sumSync(4, 5, next); + +// server.method(methods) + +var config = { + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000, + generateTimeout: 100 + } + } +}; +server.method(config); +server.method([config]); diff --git a/types/hapi/test/server/methods.ts b/types/hapi/test/server/methods.ts new file mode 100644 index 0000000000..1e2060c3e8 --- /dev/null +++ b/types/hapi/test/server/methods.ts @@ -0,0 +1,17 @@ + +// From https://hapijs.com/api/16.1.1#servermethods + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); + +const add = function (a: number, b: number, next: (err: Error | null, result: number) => void) { + + return next(null, a + b); +}; + +server.method('add', add); + +server.methods.add(1, 2, (err: Error | null, result: number) => { + + // result === 3 +}); diff --git a/types/hapi/test/server/mime.ts b/types/hapi/test/server/mime.ts new file mode 100644 index 0000000000..e2dd25529b --- /dev/null +++ b/types/hapi/test/server/mime.ts @@ -0,0 +1,21 @@ + +// From https://hapijs.com/api/16.1.1#servermime + +import * as Hapi from 'hapi'; + +const options: Hapi.ServerOptions = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } +}; + +const server = new Hapi.Server(options); +server.mime.path('code.js').type === 'application/javascript'; +server.mime.path('file.npm').type === 'node/module'; diff --git a/types/hapi/test/server/new.ts b/types/hapi/test/server/new.ts new file mode 100644 index 0000000000..24ac654ecd --- /dev/null +++ b/types/hapi/test/server/new.ts @@ -0,0 +1,65 @@ +'use strict'; + +import * as Hapi from 'hapi'; + +new Hapi.Server(); +new Hapi.Server({ + app: {some: 'values'}, + cache: require('catbox-redis'), +}); + +const server = new Hapi.Server({ + cache: require('catbox-redis'), + load: { + sampleInterval: 1000 + } +}); + +// Specific cache configuration options +new Hapi.Server({ + cache: { + engine: require('catbox-redis'), + // name: 'optionally omitted when only a single cache used', + } +}); +new Hapi.Server({ + cache: [{ + engine: require('catbox-redis'), + name: 'unique 1', + }, + { + engine: require('catbox-redis'), + name: 'unique 2', + shared: true, + otherOptions: 'will be passed to the catbox strategy', + }] +}); +new Hapi.Server({ + cache: [{ + engine: require('catbox-redis'), + }, + // Does not correctly error but will be caught by hapi at runtime + { + engine: require('catbox-redis'), + }] +}); + +new Hapi.Server({ + connections: { + app: {}, + compression: false, + load: { + maxHeapUsedBytes: 10, + maxRssBytes: 10, + maxEventLoopDelay: 10, + }, + plugins: { + 'some-plugin-name': {options: 'here'} + }, + router: { + isCaseSensitive: false, + stripTrailingSlash: true, + }, + routes: {} + } +}) diff --git a/types/hapi/test/server/on.ts b/types/hapi/test/server/on.ts new file mode 100644 index 0000000000..08802fda96 --- /dev/null +++ b/types/hapi/test/server/on.ts @@ -0,0 +1,43 @@ + +// From https://hapijs.com/api/16.1.1#serveroncriteria-listener +// From https://hapijs.com/api/16.1.1#server-events + +import * as Hapi from 'hapi'; + +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.event('test'); +server.on('test', (update: Update) => console.log(update)); +type Update = string; +var toSend: Update = 'hello'; +server.emit('test', toSend); + +server.on('log', (event, tags) => { + + if (tags.error) { + console.log('Server error: ' + (event.data || 'unspecified')); + } +}); + +server.on('request', (request, event, tags) => { + + if (tags.received) { + console.log('New request: ' + request.id); + } +}); + +server.on('request-error', (request, err) => { + + console.log('Error response (500) sent for request: ' + request.id + ' because: ' + err.message); +}); + +server.on('response', (request) => { + + console.log('Response sent for request: ' + request.id); +}); + +server.on('route', (route, connection, server) => { + + console.log('New route added: ' + route.path); +}); diff --git a/types/hapi/test/server/once.ts b/types/hapi/test/server/once.ts new file mode 100644 index 0000000000..55fdb08ec2 --- /dev/null +++ b/types/hapi/test/server/once.ts @@ -0,0 +1,14 @@ + +// From https://hapijs.com/api/16.1.1#serveroncecriteria-listener + +import * as Hapi from 'hapi'; + +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.event('test'); +server.once('test', (update: Update) => console.log(update)); +type Update = string; +var toSend: Update = 'hello'; +server.emit('test', toSend); +server.emit('test', toSend); // Ignored diff --git a/types/hapi/test/server/path.ts b/types/hapi/test/server/path.ts new file mode 100644 index 0000000000..20479a795f --- /dev/null +++ b/types/hapi/test/server/path.ts @@ -0,0 +1,13 @@ + +// From https://hapijs.com/api/16.1.1#serverpathrelativeto + +import * as Hapi from 'hapi'; + +var register: Hapi.PluginFunction<{}> = function (server, options, next) { + + // Assuming the Inert plugin was registered previously + + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); +}; diff --git a/types/hapi/test/server/plugins.ts b/types/hapi/test/server/plugins.ts new file mode 100644 index 0000000000..2ce13ffb2f --- /dev/null +++ b/types/hapi/test/server/plugins.ts @@ -0,0 +1,15 @@ + +// From https://hapijs.com/api/16.1.1#serverplugins + +import * as Hapi from 'hapi'; + +var registerFunction: Hapi.PluginFunction<{}> = function(server, options, next) { + + server.expose('key', 'value'); + server.plugins.example.key === 'value'; + return next(); +}; + +registerFunction.attributes = { + name: 'example' +}; diff --git a/types/hapi/test/server/realm.ts b/types/hapi/test/server/realm.ts new file mode 100644 index 0000000000..31f764b7ef --- /dev/null +++ b/types/hapi/test/server/realm.ts @@ -0,0 +1,10 @@ + +// From https://hapijs.com/api/16.1.1#serverrealm + +import * as Hapi from 'hapi'; + +var registerFunction: Hapi.PluginFunction<{}> = function(server, options, next) { + + console.log(server.realm.modifiers.route.prefix); + return next(); +}; diff --git a/types/hapi/test/server/register.ts b/types/hapi/test/server/register.ts new file mode 100644 index 0000000000..c04e0b16bc --- /dev/null +++ b/types/hapi/test/server/register.ts @@ -0,0 +1,18 @@ + +// From https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback + +import * as Hapi from 'hapi'; + +const server = new Hapi.Server(); + +server.register({ + register: require('plugin_name'), + options: { + message: 'hello' + } +}, (err) => { + + if (err) { + console.log('Failed loading plugin'); + } +}); diff --git a/types/hapi/test/server/route.ts b/types/hapi/test/server/route.ts new file mode 100644 index 0000000000..0402fd3e89 --- /dev/null +++ b/types/hapi/test/server/route.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#serverrouteoptions + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); +server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } +]); diff --git a/types/hapi/test/server/select.ts b/types/hapi/test/server/select.ts new file mode 100644 index 0000000000..8a25f45abd --- /dev/null +++ b/types/hapi/test/server/select.ts @@ -0,0 +1,11 @@ + +// From https://hapijs.com/api/16.1.1#serverselectlabels + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80, labels: ['a', 'b'] }); +server.connection({ port: 8080, labels: ['a', 'c'] }); +server.connection({ port: 8081, labels: ['b', 'c'] }); + +const a = server.select('a'); // 80, 8080 +const ac = a.select('c'); // 8080 diff --git a/types/hapi/test/server/settings.ts b/types/hapi/test/server/settings.ts new file mode 100644 index 0000000000..c2ec9ce3ed --- /dev/null +++ b/types/hapi/test/server/settings.ts @@ -0,0 +1,11 @@ + +// From https://hapijs.com/api/16.1.1#serversettings + +import * as Hapi from 'hapi'; +const server = new Hapi.Server({ + app: { + key: 'value' + } +}); + +server.settings.app === { key: 'value' }; diff --git a/types/hapi/test/server/start.ts b/types/hapi/test/server/start.ts new file mode 100644 index 0000000000..a15bb79740 --- /dev/null +++ b/types/hapi/test/server/start.ts @@ -0,0 +1,13 @@ + +// From https://hapijs.com/api/16.1.1#serverstartcallback + +import * as Hapi from 'hapi'; +import * as Hoek from 'hoek'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.start((err) => { + + Hoek.assert(!err, err!); + console.log('Server started at: ' + server.info!.uri); +}); diff --git a/types/hapi/test/server/state.ts b/types/hapi/test/server/state.ts new file mode 100644 index 0000000000..2035343a17 --- /dev/null +++ b/types/hapi/test/server/state.ts @@ -0,0 +1,38 @@ + +// From https://hapijs.com/api/16.1.1#serverstatename-options + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +// Set cookie definition + +server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' +}); + +// Set state in route handler + +const handler: Hapi.RouteHandler = function (request, reply) { + + let session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + + session.last = Date.now(); + + return reply('Success').state('session', session); +}; + +// Example 2 + +server.on('request-internal', (request, event, tags) => { + + if (tags.error && tags.state) { + console.error(event); + } +}); diff --git a/types/hapi/test/server/stop.ts b/types/hapi/test/server/stop.ts new file mode 100644 index 0000000000..ddfd07aa8f --- /dev/null +++ b/types/hapi/test/server/stop.ts @@ -0,0 +1,11 @@ + +// From https://hapijs.com/api/16.1.1#serverstopoptions-callback + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +server.stop({ timeout: 60 * 1000 }, (err) => { + + console.log('Server stopped'); +}); diff --git a/types/hapi/test/server/table.ts b/types/hapi/test/server/table.ts new file mode 100644 index 0000000000..abe0707c76 --- /dev/null +++ b/types/hapi/test/server/table.ts @@ -0,0 +1,9 @@ + +// From https://hapijs.com/api/16.1.1#servertablehost + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.connection({ port: 80, host: 'example.com' }); +server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + +const table = server.table(); diff --git a/types/hapi/test/server/version.ts b/types/hapi/test/server/version.ts new file mode 100644 index 0000000000..064e87e3cd --- /dev/null +++ b/types/hapi/test/server/version.ts @@ -0,0 +1,6 @@ + +// From http://hapijs.com/api#serversettings + +import * as Hapi from 'hapi'; +const server = new Hapi.Server(); +server.version === '8.0.0' diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index c7385884c3..f8d5b055e2 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -17,6 +17,76 @@ }, "files": [ "index.d.ts", - "hapi-tests.ts" + "test/connection/table.ts", + "test/getting-started/01-creating-a-server.ts", + "test/getting-started/02-adding-routes.ts", + "test/getting-started/03-serving-static-content.ts", + "test/getting-started/04-using-plugins.ts", + "test/path/catch-all.ts", + "test/path/parameters.ts", + "test/plugins/options.ts", + "test/reply/continue.ts", + "test/reply/entity.ts", + "test/reply/redirect.ts", + "test/reply/reply.ts", + "test/reply/state_cookie.ts", + "test/request/event-types.ts", + "test/request/generate-response.ts", + "test/request/get-log.ts", + "test/request/log.ts", + "test/request/set-method.ts", + "test/request/set-url.ts", + "test/request/tail.ts", + "test/response/error-representation.ts", + "test/response/error.ts", + "test/response/events.ts", + "test/response/flow-control.ts", + "test/route/additional-options.ts", + "test/route/auth.ts", + "test/route/config.ts", + "test/route/handler.ts", + "test/route/prerequisites.ts", + "test/route/public-interface.ts", + "test/server/app.ts", + "test/server/auth.ts", + "test/server/bind.ts", + "test/server/cache.ts", + "test/server/connection-options.ts", + "test/server/connections.ts", + "test/server/decoder.ts", + "test/server/decorate.ts", + "test/server/dependency.ts", + "test/server/emit.ts", + "test/server/encoder.ts", + "test/server/event.ts", + "test/server/expose.ts", + "test/server/ext.ts", + "test/server/handler.ts", + "test/server/info.ts", + "test/server/initialize.ts", + "test/server/inject.ts", + "test/server/listener.ts", + "test/server/load.ts", + "test/server/log.ts", + "test/server/lookup.ts", + "test/server/match.ts", + "test/server/method.ts", + "test/server/methods.ts", + "test/server/mime.ts", + "test/server/new.ts", + "test/server/on.ts", + "test/server/once.ts", + "test/server/path.ts", + "test/server/plugins.ts", + "test/server/realm.ts", + "test/server/register.ts", + "test/server/route.ts", + "test/server/select.ts", + "test/server/settings.ts", + "test/server/start.ts", + "test/server/state.ts", + "test/server/stop.ts", + "test/server/table.ts", + "test/server/version.ts" ] } \ No newline at end of file diff --git a/types/hapi/tslint.json b/types/hapi/tslint.json deleted file mode 100644 index 56c322f9d7..0000000000 --- a/types/hapi/tslint.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "indent": [true, "tabs"], - - // All TODOs - "ban-types": false, - "callable-types": false, - "interface-name": false, - "jsdoc-format": false, - "max-line-length": false, - "no-empty-interface": false, - "unified-signatures": false - } -} diff --git a/types/hapi/v12/hapi-tests.ts b/types/hapi/v12/hapi-tests.ts new file mode 100644 index 0000000000..32d1aff704 --- /dev/null +++ b/types/hapi/v12/hapi-tests.ts @@ -0,0 +1,114 @@ +// Copied directly from 918608a5e007d925f4f60a275881057f07c12619 which seems to +// be the last author to work on v12.0 + + +import * as Hapi from 'hapi'; + +// Create a server with a host and port +var server = new Hapi.Server(); +server.connection({ + host: "localhost", + port: 8000 +}); + +// Add plugins +var plugin: any = { + register: function (plugin: Object, options: Object, next: Function) { + next(); + } +}; + +plugin.register.attributes = { + name: "test", + version: "1.0.0" +}; + +// optional options parameter +server.register({}, function (err) {}); + +// optional options.routes.vhost parameter +server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); + +//server.pack.register(plugin, (err: Object) => { +// if (err) { throw err; } +//}); + +//server.pack.register([plugin], (err: Object) => { +// if (err) { throw err; } +//}); + +// Add server method +var add = function (a: number, b: number, next: (err: any, result?: any, ttl?: number) => void) { + next(null, a + b); +}; + +server.method("sum", add);//, { cache: { expiresIn: 2000 } }); + +server.methods["sum"](4, 5, (err: any, result: any) => { + console.log(result); +}); + +var addArray = function (array: Array, next: (err: any, result?: any, ttl?: number) => void) { + var sum: number = 0; + array.forEach((item: number) => { + sum += item; + }); + next(null, sum); +}; + +server.method("sumObj", addArray, { + //cache: { expiresIn: 2000 }, + generateKey: (array: Array) => { + return array.join(','); + } +}); + +server.methods["sumObj"]([5, 6], (err: any, result: any) => { + console.log(result); +}); + +// Add the route +server.route({ + method: 'GET', + path: '/hello', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world'); + } +}); + +server.route([{ + method: 'GET', + path: '/hello2', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world2'); + } +}]); + +// config.validate parameters should be optional +server.route([{ + method: 'GET', + path: '/hello2', + handler: function(request: Hapi.Request, reply: Function) { + reply('hello world2'); + }, + config: { + validate: { + } + } +}]); + +// Should be able to chain reply options +server.route([{ + method: 'GET', + path: '/chained-notation', + handler: function(request: Hapi.Request, reply: Hapi.IReply) { + reply('chained-notation') + .bytes(16) + .code(200) + .type('text/plain') + .header('X-Custom', 'some-value'); + } +}]); + +// Start the server +server.start(); diff --git a/types/hapi/v12/index.d.ts b/types/hapi/v12/index.d.ts new file mode 100644 index 0000000000..13c9e7a28d --- /dev/null +++ b/types/hapi/v12/index.d.ts @@ -0,0 +1,2331 @@ +// Type definitions for hapi 12.0.1 +// Project: http://github.com/spumko/hapi +// Definitions by: Jason Swearingen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Note/Disclaimer: +// Copied directly from 918608a5e007d925f4f60a275881057f07c12619 which seems to +// be the last author to work on v12.0 + + +/// + +declare module "hapi" { + import http = require("http"); + import stream = require("stream"); + import Events = require("events"); + + interface IDictionary { + [key: string]: T; + } + + interface IThenable { + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IThenable; + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IThenable; + } + + interface IPromise extends IThenable { + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IPromise; + then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IPromise; + catch(onRejected?: (error: any) => U | IThenable): IPromise; + } + + /** Boom Module for errors. https://github.com/hapijs/boom + * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ + export interface IBoom extends Error { + /** if true, indicates this is a Boom object instance. */ + isBoom: boolean; + /** convenience bool indicating status code >= 500. */ + isServer: boolean; + /** the error message. */ + message: string; + /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ + output: { + /** the HTTP status code (typically 4xx or 5xx). */ + statusCode: number; + /** an object containing any HTTP headers where each key is a header name and value is the header content. */ + headers: IDictionary; + /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ + payload: { + /** the HTTP status code, derived from error.output.statusCode. */ + statusCode: number; + /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ + error: string; + /** the error message derived from error.message. */ + message: string; + }; + }; + /** reformat()rebuilds error.output using the other object properties. */ + reformat(): void; + + } + + /** cache functionality via the "CatBox" module. */ + export interface ICatBoxCacheOptions { + /** a prototype function or catbox engine object. */ + engine: any; + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ + name?: string; + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + } + + /** Any connections configuration server defaults can be included to override and customize the individual connection. */ + export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ + host?: string; + /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ + address?: string; + /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ + port?: string | number; + /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ + uri?: string; + /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ + listener?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ + statuses: number[]; + }; + /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ + labels?: string | string[]; + /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; + + } + + export interface IConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: IRouteAdditionalConfigurationOptions; + state?: IServerState; + } + + /** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ + export interface IServerOptions { + /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). + a configuration object with the following options: + enginea prototype function or catbox engine object. + namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. + sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + other options passed to the catbox strategy used. + an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ + cache?: string | ICatBoxCacheOptions | Array | any; + /** sets the default connections configuration which can be overridden by each connection where: */ + connections?: IConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ + debug?: boolean | { + /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log: string[]; + /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ + request: string[]; + }; + /** file system related settings*/ + files?: { + /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ + etagsCacheMaxSize?: number; + }; + /** process load monitoring*/ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ + sampleInterval?: number; + }; + + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ + mime?: any; + /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ + minimal?: boolean; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ + plugins?: IDictionary; + + } + + export interface IServerViewCompile { + (template: string, options: any): void; + (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; + } + + export interface IServerViewsAdditionalOptions { + /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ + path?: string; + /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + */ + partialsPath?: string; + /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ + helpersPath?: string; + /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ + relativeTo?: string; + + /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ + layout?: boolean; + /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ + layoutPath?: string; + /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ + layoutKeywork?: string; + /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ + encoding?: string; + /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ + isCached?: boolean; + /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ + allowAbsolutePaths?: boolean; + /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ + allowInsecureAccess?: boolean; + /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ + compileOptions?: any; + /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ + runtimeOptions?: any; + /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ + contentType?: string; + /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ + compileMode?: string; + /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ + context?: any; + } + + export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { + /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. + * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ + module: { + compile?(template: any, options: any): (context: any, options: any) => void; + compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + }; + } + + /**Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods. + */ + export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { + /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ + engines: IDictionary | IServerViewsEnginesOptions; + /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ + defaultExtension?: string; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply { + (err: Error, + result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any + ): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; + + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + * The data argument is only used for passing back authentication data and is ignored elsewhere. */ + continue(credentialData?: any): void; + + /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ + file( + /** the file path. */ + path: string, + /** optional settings: */ + options?: { + /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /** specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed: boolean; + }): void; + /** Concludes the handler activity by returning control over to the router with a templatized view response. + the response flow control rules apply. */ + + view( + /** the template filename and path, relative to the templates path configured via the server views manager. */ + template: string, + /** optional object used by the template to render context-specific result. Defaults to no context {}. */ + context?: {}, + /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ + options?: any): Response; + /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed + The response flow control rules do not apply. */ + close(options?: { + /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ + end?: boolean; + }): void; + /** Proxies the request to an upstream endpoint. + the response flow control rules do not apply. */ + + proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ + options: IProxyHandlerConfig): void; + /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). + he response flow control rules apply. */ + redirect(uri: string): ResponseRedirect; + } + + export interface ISessionHandler { + (request: Request, reply: IReply): void; + } + export interface IRequestHandler { + (request: Request): T; + } + + + export interface IFailAction { + (source: string, error: any, next: () => void): void + } + /** generates a reverse proxy handler */ + export interface IProxyHandlerConfig { + /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ + host?: string; + /** the upstream service port. */ + port?: number; + /** The protocol to use when making a request to the proxied host: + 'http' + 'https'*/ + protocol?: string; + /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ + uri?: string; + /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ + passThrough?: boolean; + /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ + localStatePassThrough?: boolean; + /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ + rejectUnauthorized?: boolean; + /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ + xforward?: boolean; + /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ + redirects?: boolean | number; + /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ + timeout?: number; + /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: + request - is the incoming request object. + callback - is function(err, uri, headers) where: + err - internal error condition. + uri - the absolute proxy URI. + headers - optional object where each key is an HTTP request header and the value is the header content.*/ + mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; + /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ + onResponse?: ( + err: any, + res: http.ServerResponse, + req: Request, + reply: IReply, + settings: IProxyHandlerConfig, + ttl: number + ) => void; + /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ + ttl?: number; + /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ + agent?: http.Agent; + /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ + maxSockets?: boolean | number; + } + /** TODO: fill in joi definition */ + export interface IJoi { + + } + /** a validation function using the signature function(value, options, next) */ + export interface IValidationFunction { + + (/** the object containing the path parameters. */ + value: any, + /** the server validation options. */ + options: any, + /** the callback function called when validation is completed. */ + next: (err: any, value: any) => void): void; + } + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + export interface IRouteFailFunction { + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + ( + /** - the [request object]. */ + request: Request, + /** the continuation reply interface. */ + reply: IReply, + /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ + source: string, + /** the error object prepared for the client response (including the validation function error under error.data). */ + error: any): void; + } + + /** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ + export interface IRouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. + a string with the name of an authentication strategy registered with server.auth.strategy(). + an object */ + auth?: boolean | string | + { + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + 'required'authentication is required. + 'optional'authentication is optional (must be valid if present). + 'try'same as 'optional' but allows for invalid authentication. */ + mode?: string; + /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies?: string | Array; + /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: + falseno payload authentication.This is the default value. + 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. + 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ + payload?: string; + /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ + scope?: string | Array | boolean; + /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: + anythe authentication can be on behalf of a user or application.This is the default value. + userthe authentication must be on behalf of a user. + appthe authentication must be on behalf of an application. */ + entity?: string; + /** + * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming + * request and access is granted if at least one rule matches. Each rule object must include at least one of: + */ + access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; + }; + /** an object passed back to the provided handler (via this) when called. */ + bind?: any; + /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ + cache?: { + /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: + fault'no privacy flag.This is the default setting. + 'public'mark the response as suitable for public caching. + 'private'mark the response as suitable only for private caching. */ + privacy: string; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ + expiresIn: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ + expiresAt: string; + }; + /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ + cors?: { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ + origin?: Array; + /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ + matchOrigin?: boolean; + /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ + isOriginExposed?: boolean; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ + headers?: string[]; + /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ + methods?: string[]; + /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ + additionalMethods?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ + credentials?: boolean; + /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ + override?: boolean; + }; + /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ + files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ + relativeTo: string; + }; + + /** an alternative location for the route handler option. */ + handler?: ISessionHandler | string | IRouteHandlerConfig; + /** an optional unique identifier used to look up the route using server.lookup(). */ + id?: number; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ + json?: { + /** the replacer function or array.Defaults to no action. */ + replacer?: Function | string[]; + /** number of spaces to indent nested object keys.Defaults to no indentation. */ + space?: number | string; + /** string suffix added after conversion to JSON string.Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ + jsonp?: string; + /** determines how the request payload is processed: */ + payload?: { + /** the type of payload representation requested. The value must be one of: + 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. + 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ + output?: string; + /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + 'application/json' + 'application/x-www-form-urlencoded' + 'application/octet-stream' + 'text/ *' + 'multipart/form-data' */ + parse?: string | boolean; + /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ + uploads?: string; + /** determines how to handle payload parsing errors. Allowed values are: + 'error'return a Bad Request (400) error response. This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action and continue processing the request. */ + failAction?: string; + }; + /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: IDictionary; + /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ + pre?: any[]; + /** validation rules for the outgoing response payload (response body).Can only validate object response: */ + response?: { + /** the default HTTP status code when the payload is empty. Value can be 200 or 204. + Note that a 200 status code is converted to a 204 only at the time or response transmission + (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ + emptyStatusCode?: number; + /** the default response object validation rules (for all non-error responses) expressed as one of: + true - any payload allowed (no validation performed). This is the default. + false - no payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + value - the object containing the response object. + options - the server validation options. + next(err) - the callback function called when validation is completed. */ + schema?: boolean | any; + /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ + status?: { [statusCode: number] : boolean | any }; + /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ + sample?: number; + /** defines what to do when a response fails validation.Options are: + errorreturn an Internal Server Error (500) error response.This is the default value. + loglog the error but send the response. */ + failAction?: string; + /** if true, applies the validation rule changes to the response.Defaults to false. */ + modify?: boolean; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ + security?: boolean | { + /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ + hsts?: boolean | number | { + /** the max- age portion of the header, as a number.Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubdomains flag to the header. */ + includeSubdomains?: boolean; + /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ + preload?: boolean; + }; + /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe?: { + /** either 'deny', 'sameorigin', or 'allow-from' */ + rule: string; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ + xss?: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ + noOpen?: boolean; + /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ + noSniff?: boolean; + }; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ + parse: boolean; + /** determines how to handle cookie parsing errors.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action. */ + failAction: string; + }; + /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ + validate?: { + /** validation rules for incoming request headers.Values allowed: + * trueany headers allowed (no validation performed).This is the default. + falseno headers allowed (this will cause all valid HTTP requests to fail). + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the request headers. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. + */ + headers?: boolean | IJoi | IValidationFunction; + + + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: + trueany path parameters allowed (no validation performed).This is the default. + falseno path variables allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the path parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + params?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: + trueany query parameters allowed (no validation performed).This is the default. + falseno query parameters allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the query parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + query?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request payload (request body).Values allowed: + trueany payload allowed (no validation performed).This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the payload object. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + payload?: boolean | IJoi | IValidationFunction; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** determines how to handle invalid requests.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'log the error but continue processing the request. + 'ignore'take no action. + OR a custom error handler function with the signature 'function(request, reply, source, error)` where: + requestthe request object. + replythe continuation reply interface. + sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). + errorthe error object prepared for the client response (including the validation function error under error.data). */ + failAction?: string | IRouteFailFunction; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ + server: boolean | number; + /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ + socket: boolean | number; + }; + + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route description used for generating documentation (string). + */ + description?: string; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route notes used for generating documentation (string or array of strings). + */ + notes?: string | string[]; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route tags used for generating documentation (array of strings). + */ + tags?: string[] + } + + /** + * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches + */ + export interface IRouteAdditionalConfigurationAuthAccess { + /** + * the application scope required to access the route. Value can be a scope string or an array of scope strings. + * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, + * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' + * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties + * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, + * such as 'user-{params.id}'. Defaults to false (no scope requirements). + */ + scope?: string | Array | boolean; + /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: + * any - the authentication can be on behalf of a user or application. This is the default value. + * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. + * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + */ + entity?: string; + } + + /** server.realm http://hapijs.com/api#serverrealm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + }; + */ + export interface IServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ + modifiers: { + /** routes preferences: */ + route: { + /** - the route path prefix used by any calls to server.route() from the server. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + }; + + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: IDictionary; + /** settings overrides */ + settings: { + files: { + relativeTo: any; + }; + bind: any; + } + } + /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ + export interface IServerState { +/** - the cookie name string. */name: string; + +/** - are the optional cookie settings: */options: { +/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; +/** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; +/** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean +/** - the path scope.Defaults to null (no path).*/path: any; +/** - the domain scope.Defaults to null (no domain). */domain: any; + /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization. Options are: + 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON-stringified than encoded using Base64. + 'form' - object value is encoded using the x-www-form-urlencoded method. + 'iron' - Encrypts and sign the value using iron.*/ + encoding: string; +/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { +/** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; +/** - password used for HMAC key generation.*/password: string; + }; +/** - password used for 'iron' encoding.*/password: string; +/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; +/** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; +/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; +/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; +/** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; + }; + } + + export interface IFileHandlerConfig { + /** a path string or function as described above.*/ + path: string; + /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ + lookupCompressed: boolean; + } + + /**http://hapijs.com/api#route-handler + Built-in handlers + + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ + export interface IRouteHandlerConfig { + /** generates a static file endpoint for serving a single file. file can be set to: + a relative or absolute file path string (relative paths are resolved based on the route files configuration). + a function with the signature function(request) which returns the relative or absolute file path. + an object with the following options */ + file?: string | IRequestHandler | IFileHandlerConfig; + /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. + listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. + defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ + directory?: { + path: string | Array | IRequestHandler | IRequestHandler>; + index?: boolean | string | string[]; + listing?: boolean; + showHidden?: boolean; + redirectToSlash?: boolean; + lookupCompressed?: boolean; + defaultExtension?: string; + }; + proxy?: IProxyHandlerConfig; + view?: string | { + template: string; + context: { + payload: any; + params: any; + query: any; + pre: any; + } + }; + config?: { + handler: any; + bind: any; + app: any; + plugins: { + [name: string]: any; + }; + pre: Array<() => void>; + validate: { + headers: any; + params: any; + query: any; + payload: any; + errorFields?: any; + failAction?: string | IFailAction; + }; + payload: { + output: { + data: any; + stream: any; + file: any; + }; + parse?: any; + allow?: string | Array; + override?: string; + maxBytes?: number; + uploads?: number; + failAction?: string; + }; + response: { + schema: any; + sample: number; + failAction: string; + }; + cache: { + privacy: string; + expiresIn: number; + expiresAt: number; + }; + auth: string | boolean | { + mode: string; + strategies: Array; + payload?: boolean | string; + tos?: boolean | string; + scope?: string | Array; + entity: string; + }; + cors?: boolean; + jsonp?: string; + description?: string; + notes?: string | Array; + tags?: Array; + }; + } + /** Route configuration + The route configuration object*/ + export interface IRouteConfiguration { + /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ + path: string; + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ + method: string | string[]; + /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ + vhost?: string; + /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ + handler: ISessionHandler | string | IRouteHandlerConfig; + /** - additional route options.*/ + config?: IRouteAdditionalConfigurationOptions; + } + /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ + export interface IRoute { + + + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | Array; + /** the [active realm] associated with the route.*/ + realm: IServerRealm; + /** the [route options] object with all defaults applied. */ + settings: IRouteAdditionalConfigurationOptions; + } + + export interface IServerAuthScheme { + /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: + request - the request object. + reply - the reply interface the authentication method must call when done authenticating the request where: + reply(err, response, result) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + result - an object containing: + credentials - the authenticated credentials. + artifacts - optional authentication artifacts. + reply.continue(result) - is called if authentication succeeded where: + result - same object as result above. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var scheme = function (server, options) { + return { + authenticate: function (request, reply) { + var req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply(null, { credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme);*/ + authenticate(request: Request, reply: IReply): void; + /** payload(request, reply) - optional function called to authenticate the request payload where: + request - the request object. + reply(err, response) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + reply.continue() - is called if payload authentication succeeded. + When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ + payload?(request: Request, reply: IReply): void; + /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: + request - the request object. + reply(err, response) - is called if an error occurred where: + err - any authentication error. + response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + reply.continue() - is called if the operation succeeded.*/ + response?(request: Request, reply: IReply): void; + /** an optional object */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ + payload: boolean; + } + } + + + + export interface IServerInject { + (options: string | { + /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ + method: string; + /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ + url: string; + /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ + headers?: IDictionary; + /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ + payload?: string | {} | Buffer; + /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ + credentials?: any; + /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ + artifacts?: any; + /** sets the initial value of request.app*/ + app?: any; + /** sets the initial value of request.plugins*/ + plugins?: any; + /** allows access to routes with config.isInternal set to true. Defaults to false.*/ + allowInternals?: boolean; + /** sets the remote address for the incoming connection.*/ + remoteAddress?: boolean; + /**object with options used to simulate client request stream conditions for testing: + error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + end - if false, does not end the stream. Defaults to true.*/ + simulate?: { + error: boolean; + close: boolean; + end: boolean; + }; + }, + callback: ( + /**the response object where: + statusCode - the HTTP status code. + headers - an object containing the headers set. + payload - the response payload string. + rawPayload - the raw response payload buffer. + raw - an object with the injection request and response objects: + req - the simulated node request object. + res - the simulated node response object. + result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + request - the request object.*/ + res: { statusCode: number; headers: IDictionary; payload: string; rawPayload: Buffer; raw: { req: http.ClientRequest; res: http.ServerResponse }; result: string; request: Request }) => void + ): void; + + } + + + /** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path.*/ + export interface IConnectionTable { + info: any; + labels: any; + table: IRoute[]; + } + + export interface ICookieSettings { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl?: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure?: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly?: boolean; + /** - the path scope.Defaults to null (no path).*/ + path?: string; + /** - the domain scope.Defaults to null (no domain).*/ + domain?: any; + /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue?: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization.Options are: + 'none' - no encoding.When used, the cookie value must be a string.This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON- stringified than encoded using Base64. + 'form' - object value is encoded using the x- www - form - urlencoded method. */ + encoding?: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: + integrity - algorithm options.Defaults to require('iron').defaults.integrity. + password - password used for HMAC key generation. */ + sign?: { integrity: any; password: string; } + password?: string; + iron?: any; + ignoreErrors?: boolean; + clearInvalid?: boolean; + strictHeader?: boolean; + passThrough?: any; + } + + /** method - the method function with the signature is one of: + function(arg1, arg2, ..., argn, next) where: + arg1, arg2, etc. - the method function arguments. + next - the function called when the method is done with the signature function(err, result, ttl) where: + err - error response if the method failed. + result - the return value. + ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + function(arg1, arg2, ..., argn) where: + arg1, arg2, etc. - the method function arguments. + the callback option is set to false. + the method must returns a value (result, Error, or a promise) or throw an Error.*/ + export interface IServerMethod { + //(): void; + //(next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any): void; + //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any, arg2: any): void; + (...args: any[]): void; + + } + /** options - optional configuration: + bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. + cache - the same cache configuration used in server.cache(). + callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ + export interface IServerMethodOptions { + bind?: any; + cache?: ICatBoxCacheOptions; + callback?: boolean; + generateKey?(args: any[]): string; + } + /** Request object + + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + Request events + + The request object supports the following events: + + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the request payload finished reading. The event method signature is function (). + 'disconnect' - emitted when a request errors or aborts unexpectedly. + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + var hash = Crypto.createHash('sha1'); + request.on('peek', function (chunk) { + + hash.update(chunk); + }); + + request.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + request.once('disconnect', function () { + + console.error('request aborted'); + }); + + return reply.continue(); + });*/ + export class Request extends Events.EventEmitter { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** authentication information*/ + auth: { + /** true is the request has been successfully authenticated, otherwise false.*/ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ + artifacts: any; + /** the route authentication mode.*/ + mode: any; + /** the authentication error is failed and mode set to 'try'.*/ + error: any; + /** an object used by the ['cookie' authentication scheme] https://github.com/hapijs/hapi-auth-cookie */ + session: any + }; + /** the connection used by this request*/ + connection: ServerConnection; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ + domain: any; + /** the raw request headers (references request.raw.headers).*/ + headers: IDictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: number; + /** request information */ + info: { + /** request reception timestamp. */ + received: number; + /** request response timestamp (0 is not responded yet). */ + responded: number; + /** remote client IP address. */ + + remoteAddress: string; + /** remote client port. */ + remotePort: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com').*/ + hostname: string; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ + params: IDictionary; + /** an array containing all the path params values in the order they appeared in the path.*/ + paramsArray: string[]; + /** the request URI's path component. */ + path: string; + /** the request payload based on the route payload.output and payload.parse settings.*/ + payload: stream.Readable | Buffer | any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ + plugins: any; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ + pre: IDictionary; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ + response: Response; + /**preResponses - same as pre but represented as the response object created by the pre method.*/ + preResponses: any; + /**an object containing the query parameters.*/ + query: any; + /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ + raw: { + req: http.ClientRequest; + res: http.ServerResponse; + }; + /** the route public interface.*/ + route: IRoute; + /** the server object. */ + server: Server; + /** Special key reserved for plugins implementing session support. Plugins utilizing this key must check for null value to ensure there is no conflict with another similar server. */ + session: any; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: any; + /** complex object contining details on the url */ + url: { + /** null when i tested */ + auth: any; + /** null when i tested */ + hash: any; + /** null when i tested */ + host: any; + /** null when i tested */ + hostname: any; + href: string; + path: string; + /** path without search*/ + pathname: string; + /** null when i tested */ + port: any; + /** null when i tested */ + protocol: any; + /** querystring parameters*/ + query: IDictionary; + /** querystring parameters as a string*/ + search: string; + /** null when i tested */ + slashes: any; + }; + /** request.setUrl(url) + + Available only in 'onRequest' extension methods. + + Changes the request URI before the router begins processing the request where: + + url - the new request path value. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + });*/ + setUrl(url: string): void; + /** request.setMethod(method) + + Available only in 'onRequest' extension methods. + + Changes the request method before the router begins processing the request where: + + method - is the request HTTP method (e.g. 'GET'). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); + });*/ + setMethod(method: string): void; + /** request.log(tags, [data, [timestamp]]) + + Always available. + + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.on('request', function (request, event, tags) { + + if (tags.error) { + console.log(event); + } + }); + + var handler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); + }; + */ + log( + /** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ + tags: string | string[], + /** an optional message string or object with the application data being logged.*/ + data?: string, + /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ + timestamp?: number): void; + /** request.getLog([tags], [internal]) + + Always available. + + Returns an array containing the events matching any of the tags specified (logical OR) + request.getLog(); + request.getLog('error'); + request.getLog(['error', 'auth']); + request.getLog(['error'], true); + request.getLog(false);*/ + + getLog( + /** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ + tags?: string, + /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ + internal?: boolean): string[]; + + /** request.tail([name]) + + Available until immediately after the 'response' event is emitted. + + Adds a request tail which has to complete before the request lifecycle is complete where: + + name - an optional tail name used for logging purposes. + Returns a tail function which must be called when the tail activity is completed. + + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + + When all tails completed, the server emits a 'tail' event. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + var get = function (request, reply) { + + var dbTail = request.tail('write to database'); + + db.save('key', 'value', function () { + + dbTail(); + }); + + return reply('Success!'); + }; + + server.route({ method: 'GET', path: '/', handler: get }); + + server.on('tail', function (request) { + + console.log('Request completed including db activity'); + });*/ + tail( + /** an optional tail name used for logging purposes.*/ + name?: string): Function; + } + /** Response events + + The response object supports the following events: + + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onPreResponse', function (request, reply) { + + var response = request.response; + if (response.isBoom) { + return reply(); + } + + var hash = Crypto.createHash('sha1'); + response.on('peek', function (chunk) { + + hash.update(chunk); + }); + + response.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + return reply.continue(); + });*/ + export class Response extends Events.EventEmitter { + isBoom: boolean; + /** the HTTP response status code. Defaults to 200 (except for errors).*/ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ + headers: IDictionary; + /** the value provided using the reply interface.*/ + source: any; + /** a string indicating the type of source with available values: + 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + 'buffer' - a Buffer. + 'view' - a view generated with reply.view(). + 'file' - a file generated with reply.file() of via the directory handler. + 'stream' - a Stream. + 'promise' - a Promise object. */ + variety: string; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: any; + /** settings - response handling flags: + charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. + encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. + passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. + stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. + ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. + varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ + settings: { + charset: string; + encoding: string; + passThrough: boolean; + stringify: any; + ttl: number; + varyEtag: boolean; + } + + /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + length - the header value. Must match the actual payload size.*/ + bytes(length: number): Response; + /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ + charset(charset: string): Response; + + /** sets the HTTP status code where: + statusCode - the HTTP status code.*/ + code(statusCode: number): Response; + /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ + created(uri: string): Response; + + + /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ + encoding(encoding: string): Response; + + /** etag(tag, options) - sets the representation entity tag where: + tag - the entity tag string without the double-quote. + options - optional settings where: + weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ + etag(tag: string, options: { + weak: boolean; vary: boolean; + }): Response; + + /**header(name, value, options) - sets an HTTP header where: + name - the header name. + value - the header value. + options - optional settings where: + append - if true, the value is appended to any existing header value using separator. Defaults to false. + separator - string used as separator when appending to an exiting value. Defaults to ','. + override - if false, the header value is not set if an existing value present. Defaults to true.*/ + header(name: string, value: string, options?: { + append: boolean; + separator: string; + override: boolean; + }): Response; + + /** location(uri) - sets the HTTP 'Location' header where: + uri - an absolute or relative URI used as the 'Location' header value.*/ + location(uri: string): Response; + + /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: + uri - an absolute or relative URI used to redirect the client to another resource. */ + redirect(uri: string): Response; + + /** replacer(method) - sets the JSON.stringify() replacer argument where: + method - the replacer function or array. Defaults to none.*/ + replacer(method: Function | Array): Response; + + /** spaces(count) - sets the JSON.stringify() space argument where: + count - the number of spaces to indent nested object keys. Defaults to no indentation. */ + spaces(count: number): Response; + /**state(name, value, [options]) - sets an HTTP cookie where: + name - the cookie name. + value - the cookie value. If no encoding is defined, must be a string. + options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + state(name: string, value: string, options?: any): Response; + + /** sets a string suffix when the response is process via JSON.stringify().*/ + suffix(suffix: string): void; + /** overrides the default route cache expiration rule for this response instance where: +msec - the time-to-live value in milliseconds.*/ + ttl(msec: number): void; + /** type(mimeType) - sets the HTTP 'Content-Type' header where: + mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ + type(mimeType: string): Response; + /** clears the HTTP cookie by setting an expired value where: +name - the cookie name. +options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + unstate(name: string, options?: { [key: string]: string }): void; + /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: +header - the HTTP request header name.*/ + vary(header: string): void; + } + /** When using the redirect() method, the response object provides these additional methods */ + export class ResponseRedirect extends Response { + /** sets the status code to 302 or 307 (based on the rewritable() setting) where: +isTemporary - if false, sets status to permanent. Defaults to true.*/ + temporary(isTemporary: boolean): void; + /** sets the status code to 301 or 308 (based on the rewritable() setting) where: +isPermanent - if true, sets status to temporary. Defaults to false. */ + permanent(isPermanent: boolean): void; + /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: +isRewritable - if false, sets to non-rewritable. Defaults to true. +Permanent Temporary +Rewritable 301 302(1) +Non-rewritable 308(2) 307 +Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ + rewritable(isRewritable: boolean): void; + } + /** info about a server connection */ + export interface IServerConnectionInfo { + /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ + id: string; + /** - the connection creation timestamp.*/ + created: number; + /** - the connection start timestamp (0 when stopped).*/ + started: number; + /** the connection port based on the following rules: + the configured port value before the server has been started. + the actual port assigned when no port is configured or set to 0 after the server has been started.*/ + port: number; + + /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ + host: string; + /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ + address: string; + /** - the protocol used: + 'http' - HTTP. + 'https' - HTTPS. + 'socket' - UNIX domain socket or Windows named pipe.*/ + protocol: string; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ + uri: string; + } + /** + * undocumented. The connection object constructed after calling server.connection(); + * can be accessed via server.connections; or request.connection; + */ + export class ServerConnection extends Events.EventEmitter { + domain: any; + _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; + _eventsCount: number; + settings: IServerConnectionOptions; + server: Server; + /** ex: "tcp" */ + type: string; + _started: boolean; + /** dictionary of sockets */ + _connections: { [ip_port: string]: any }; + _onConnection: Function; + registrations: any; + _extensions: any; + _requestCounter: { value: number; min: number; max: number }; + _load: any; + states: { + settings: any; cookies: any; names: any[] + }; + auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; }; + _router: any; + MSPluginsCollection: any; + applicationCache: any; + addEventListener: any; + info: IServerConnectionInfo; + } + + /** Server http://hapijs.com/api#server + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + Server events + The server object inherits from Events.EventEmitter and emits the following events: + 'log' - events logged with server.log() and server events generated internally by the framework. + 'start' - emitted when the server is started using server.start(). + 'stop' - emitted when the server is stopped using server.stop(). + 'request' - events generated by request.log(). Does not include any internally generated events. + 'request-internal' - request events generated internally by the framework (multiple events per request). + 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. + 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. + 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. + Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. + MORE EVENTS HERE: http://hapijs.com/api#server-events*/ + export class Server extends Events.EventEmitter { + + constructor(options?: IServerOptions); + /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + var Hapi = require('hapi'); + server = new Hapi.Server(); + server.app.key = 'value'; + var handler = function (request, reply) { + return reply(request.server.app.key); + }; */ + app: any; + /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + var server = new Hapi.Server(); + server.connection({ port: 80, labels: 'a' }); + server.connection({ port: 8080, labels: 'b' }); + // server.connections.length === 2 + var a = server.select('a'); + // a.connections.length === 1*/ + connections: Array; + /** When the server contains exactly one connection, info is an object containing information about the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // server.info.port === 80 + server.connection({ port: 8080 }); + // server.info === null + // server.connections[1].info.port === 8080 + */ + info: IServerConnectionInfo; + /** An object containing the process load metrics (when load.sampleInterval is enabled): + rss - RSS memory usage. + var Hapi = require('hapi'); + var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + console.log(server.load.rss);*/ + load: { + /** - event loop delay milliseconds.*/ + eventLoopDelay: number; + /** - V8 heap usage.*/ + heapUsed: number; + }; + /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + When the server contains more than one connection, each server.connections array member provides its own connection.listener. + var Hapi = require('hapi'); + var SocketIO = require('socket.io'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var io = SocketIO.listen(server.listener); + io.sockets.on('connection', function(socket) { + socket.emit({ msg: 'welcome' }); + });*/ + listener: http.Server; + + /** server.methods + An object providing access to the server methods where each server method name is an object property. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.method('add', function (a, b, next) { + return next(null, a + b); + }); + server.methods.add(1, 2, function (err, result) { + // result === 3 + });*/ + methods: IDictionary; + + /** server.mime + Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + var Hapi = require('hapi'); + var options = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } + }; + var server = new Hapi.Server(options); + // server.mime.path('code.js').type === 'application/javascript' + // server.mime.path('file.npm').type === 'node/module'*/ + mime: any; + /**server.plugins + An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + exports.register = function (server, options, next) { + server.expose('key', 'value'); + // server.plugins.example.key === 'value' + return next(); + }; + exports.register.attributes = { + name: 'example' + };*/ + plugins: IDictionary; + /** server.realm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: + route - routes preferences: + prefix - the route path prefix used by any calls to server.route() from the server. + vhost - the route virtual host settings used by any calls to server.route() from the server. + plugin - the active plugin name (empty string if at the server root). + plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. + settings - settings overrides: + files.relativeTo + bind + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + };*/ + realm: IServerRealm; + + /** server.root + The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ + root: Server; + /** server.settings + The server configuration object after defaults applied. + var Hapi = require('hapi'); + var server = new Hapi.Server({ + app: { + key: 'value' + } + }); + // server.settings.app === { key: 'value' }*/ + settings: IServerOptions; + + /** server.version + The hapi module version number. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + // server.version === '8.0.0'*/ + version: string; + + /** server.after(method, [dependencies]) + Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: + after - the method with signature function(plugin, next) where: + server - server object the after() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error which is returned back via the server.start() callback. + dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.after(function () { + // Perform some pre-start logic + }); + server.start(function (err) { + // After method already executed + }); + server.auth.default(options)*/ + after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; + + auth: { + /** server.auth.default(options) + Sets a default strategy which is applied to every route where: + options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. + The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. + The default auth strategy configuration can be accessed via connection.auth.settings.default. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + });*/ + default(options: string): void; + /** server.auth.scheme(name, scheme) + Registers an authentication scheme where: + name - the scheme name. + scheme - the method implementing the scheme with signature function(server, options) where: + server - a reference to the server object the scheme is added to. + options - optional scheme settings used to instantiate a strategy.*/ + scheme(name: string, + /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + server = new Hapi.Server(); + server.connection({ port: 80 }); + scheme = function (server, options) { + urn { + authenticate: function (request, reply) { + req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + urn reply(null, { credentials: { user: 'john' } }); + } + }; + }; + */ + scheme: (server: Server, options: any) => IServerAuthScheme): void; + + /** server.auth.strategy(name, scheme, [mode], [options]) + Registers an authentication strategy where: + name - the strategy name. + scheme - the scheme name (must be previously registered using server.auth.scheme()). + mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. + options - scheme options based on the scheme requirements. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + } + });*/ + strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; + + /** server.auth.test(strategy, request, next) + Tests a request against an authentication strategy where: + strategy - the strategy name registered with server.auth.strategy(). + request - the request object. + next - the callback function with signature function(err, credentials) where: + err - the error if authentication failed. + credentials - the authentication credentials object if authentication was successful. + Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.server.auth.test('default', request, function (err, credentials) { + if (err) { + return reply({ status: false }); + } + return reply({ status: true, user: credentials.name }); + }); + } + });*/ + test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; + }; + /** server.bind(context) + Sets a global context used as the default bind object when adding a route or an extension where: + context - the object used to bind this in handler and extension methods. + When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + var handler = function (request, reply) { + return reply(this.message); + }; + exports.register = function (server, options, next) { + var bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); + };*/ + bind(context: any): void; + + + /** server.cache(options) + Provisions a cache segment within the server cache facility where: + options - catbox policy configuration where: + expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + staleTimeout - number of milliseconds to wait before checking if an item is stale. + generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. + cache - the cache name configured in 'server.cache`. Defaults to the default cache. + segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. + shared - if true, allows multiple cache provisions to share the same segment. Default to false. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, function (err) { + cache.get('norway', function (err, value, cached, log) { + // value === { capital: 'oslo' }; + }); + });*/ + cache(options: ICatBoxCacheOptions): void; + + /** server.connection([options]) + Adds an incoming server connection + Returns a server object with the new connection selected. + Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). + Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); + var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + // server.connections.length === 2 + // web.connections.length === 1 + // admin.connections.length === 1 */ + connection(options: IServerConnectionOptions): Server; + /** server.decorate(type, property, method) + Extends various framework interfaces with custom methods where: + type - the interface being decorated. Supported types: + 'reply' - adds methods to the reply interface. + 'server' - adds methods to the Server object. + property - the object decoration key name. + method - the extension function. + Note that decorations apply to the entire server and all its connections regardless of current selection. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.decorate('reply', 'success', function () { + return this.response({ status: 'ok' }); + }); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply.success(); + } + });*/ + decorate(type: string, property: string, method: Function): void; + + /** server.dependency(dependencies, [after]) + Used within a plugin to declares a required dependency on other plugins where: + dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. + after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + server - the server the dependency() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error condition, which is returned back via the server.start() callback. + exports.register = function (server, options, next) { + server.dependency('yar', after); + return next(); + }; + var after = function (server, next) { + // Additional plugin registration logic + return next(); + };*/ + dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; + + + /** server.expose(key, value) + Used within a plugin to expose a property via server.plugins[name] where: + key - the key assigned (server.plugins[name][key]). + value - the value assigned. + exports.register = function (server, options, next) { + server.expose('util', function () { console.log('something'); }); + return next(); + };*/ + expose(key: string, value: any): void; + + /** server.expose(obj) + Merges a deep copy of an object into to the existing content of server.plugins[name] where: + obj - the object merged into the exposed properties container. + exports.register = function (server, options, next) { + server.expose({ util: function () { console.log('something'); } }); + return next(); + };*/ + expose(obj: any): void; + + /** server.ext(event, method, [options]) + Registers an extension function in one of the available extension points where: + event - the event name. + method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: + request - the request object. NOTE: Access the Response via request.response + reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + this - the object provided via options.bind or the current active context set with server.bind(). + options - an optional object with the following: + before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + bind - a context object passed back to the provided method (via this) when called. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + }); + var handler = function (request, reply) { + return reply({ status: 'ok' }); + }; + server.route({ method: 'GET', path: '/test', handler: handler }); + server.start(); + // All requests will get routed to '/test'*/ + ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + + /** server.handler(name, method) + Registers a new handler type to be used in routes where: + name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. + method - the function used to generate the route handler using the signature function(route, options) where: + route - the route public interface object. + options - the configuration object provided in the handler config. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + // Defines new handler for routes on this server + server.handler('test', function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }); + server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } + }); + server.start(); + The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + var handler = function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }; + // Change the default payload processing for this handler + handler.defaults = { + payload: { + output: 'stream', + parse: false + } + }; + server.handler('test', handler);*/ + handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var handler = function (request, reply) { + return reply('Success!'); + }; + server.route({ method: 'GET', path: '/', handler: handler }); + server.inject('/', function (res) { + console.log(res.result); + }); + */ + inject: IServerInject; + + /** server.log(tags, [data, [timestamp]]) + Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('log', function (event, tags) { + if (tags.error) { + console.log(event); + } + }); + server.log(['test', 'error'], 'Test event');*/ + log(tags: string | string[], data?: string | any, timestamp?: number): void; + /**server.lookup(id) + When the server contains exactly one connection, looks up a route configuration where: + id - the route identifier as set in the route options. + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.lookup('root'); + When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ + lookup(id: string): IRoute; + /** server.match(method, path, [host]) + When the server contains exactly one connection, looks up a route configuration where: + method - the HTTP method (e.g. 'GET', 'POST'). + path - the requested path (must begin with '/'). + host - optional hostname (to match against routes with vhost). + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.match('get', '/'); + When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ + match(method: string, path: string, host?: string): IRoute; + + + + + /** server.method(name, method, [options]) + Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + Methods are registered via server.method(name, method, [options]) + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Simple arguments + var add = function (a, b, next) { + return next(null, a + b); + }; + server.method('sum', add, { cache: { expiresIn: 2000 } }); + server.methods.sum(4, 5, function (err, result) { + console.log(result); + }); + // Object argument + var addArray = function (array, next) { + var sum = 0; + array.forEach(function (item) { + sum += item; + }); + return next(null, sum); + }; + server.method('sumObj', addArray, { + cache: { expiresIn: 2000 }, + generateKey: function (array) { + return array.join(','); + } + }); + server.methods.sumObj([5, 6], function (err, result) { + console.log(result); + }); + // Synchronous method with cache + var addSync = function (a, b) { + return a + b; + }; + server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); + server.methods.sumSync(4, 5, function (err, result) { + console.log(result); + }); */ + method( + /** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ + name: string, + method: IServerMethod, + options?: IServerMethodOptions): void; + + + /**server.method(methods) + Registers a server method function as described in server.method() using a configuration object where: + methods - an object or an array of objects where each one contains: + name - the method name. + method - the method function. + options - optional settings. + var add = function (a, b, next) { + next(null, a + b); + }; + server.method({ + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000 + } + } + });*/ + method(methods: { + name: string; method: IServerMethod; options?: IServerMethodOptions + } | Array<{ + name: string; method: IServerMethod; options?: IServerMethodOptions + }>): void; + /**server.path(relativeTo) + Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + relativeTo - the path prefix added to any relative file path starting with '.'. + Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + exports.register = function (server, options, next) { + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); + };*/ + path(relativeTo: string): void; + /**server.register(plugins, [options], callback) + Registers a plugin where: + plugins - an object or array of objects where each one is either: + a plugin registration function. + an object with the following: + register - the plugin registration function. + options - optional options passed to the registration function when called. + options - optional registration options (different from the options passed to the registration function): + select - a string or array of string labels used to pre-select connections for plugin registration. + routes - modifiers applied to each route added by the plugin: + prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + callback - the callback function with signature function(err) where: + err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + server.register({ + register: require('plugin_name'), + options: { + message: 'hello' + } + }, function (err) { + if (err) { + console.log('Failed loading plugin'); + } + });*/ + register(plugins: any | any[], options: { + select: string | string[]; + routes: { + prefix: string; vhost?: string | string[] + }; + } + , callback: (err: any) => void): void; + + register(plugins: any | any[], callback: (err: any) => void): void; + + /**server.render(template, context, [options], callback) + Utilizes the server views manager to render a template where: + template - the template filename and path, relative to the views manager templates path (path or relativeTo). + context - optional object used by the template to render context-specific result. Defaults to no context ({}). + options - optional object used to override the views manager configuration. + callback - the callback function with signature function (err, rendered, config) where: + err - the rendering error if any. + rendered - the result view string. + config - the configuration used to render the template. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.views({ + engines: { html: require('handlebars') }, + path: __dirname + '/templates' + }); + var context = { + title: 'Views Example', + message: 'Hello, World' + }; + server.render('hello', context, function (err, rendered, config) { + console.log(rendered); + });*/ + render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; + /** server.route(options) + Adds a connection route where: + options - a route configuration object or an array of configuration objects. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); + server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } + ]);*/ + route(options: IRouteConfiguration): void; + route(options: IRouteConfiguration[]): void; + /**server.select(labels) + Selects a subset of the server's connections where: + labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, labels: ['a'] }); + server.connection({ port: 8080, labels: ['b'] }); + server.connection({ port: 8081, labels: ['c'] }); + server.connection({ port: 8082, labels: ['c','d'] }); + var a = server.select('a'); // The server with port 80 + var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 + var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ + select(labels: string | string[]): Server | Server[]; + /** server.start([callback]) + Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: + callback - optional callback when server startup is completed or failed with the signature function(err) where: + err - any startup error condition. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.start(function (err) { + console.log('Server started at: ' + server.info.uri); + });*/ + start(callback?: (err: any) => void): void; + /** server.state(name, [options]) + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions + State defaults can be modified via the server connections.routes.state configuration option. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Set cookie definition + server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' + }); + // Set state in route handler + var handler = function (request, reply) { + var session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + session.last = Date.now(); + return reply('Success').state('session', session); + }; + Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('request-internal', function (request, event, tags) { + if (tags.error && tags.state) { + console.error(event); + } + }); */ + state(name: string, options?: ICookieSettings): void; + + /** server.stop([options], [callback]) + Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + options - optional object with: + timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.stop({ timeout: 60 * 1000 }, function () { + console.log('Server stopped'); + });*/ + stop(options?: { timeout: number }, callback?: () => void): void; + /**server.table([host]) + Returns a copy of the routing table where: + host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path. + Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.table(); + When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.connections[0].table(); + //[ + // { + // method: 'get', + // path: '/example', + // settings: { ... } + // } + //] + */ + table(host?: any): IConnectionTable; + + /**server.views(options) + Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ + views(options: IServerViewsConfiguration): void; + + } +} diff --git a/types/hapi/v12/tsconfig.json b/types/hapi/v12/tsconfig.json new file mode 100644 index 0000000000..4659b7940a --- /dev/null +++ b/types/hapi/v12/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "hapi": [ + "hapi/v12" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-tests.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/hapi-tests.ts b/types/hapi/v15/hapi-tests.ts similarity index 100% rename from types/hapi/hapi-tests.ts rename to types/hapi/v15/hapi-tests.ts diff --git a/types/hapi/v15/index.d.ts b/types/hapi/v15/index.d.ts new file mode 100644 index 0000000000..86b993bfb5 --- /dev/null +++ b/types/hapi/v15/index.d.ts @@ -0,0 +1,2497 @@ +// Type definitions for hapi 15.0 +// Project: http://github.com/spumko/hapi +// Definitions by: Jason Swearingen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Note/Disclaimer: This .d.ts was created against hapi v8.x but has been incrementally upgraded to 13.x. Some newer features/changes may be missing. YMMV. + +/// + +import http = require("http"); +import stream = require("stream"); +import Events = require("events"); +import url = require("url"); + +export interface IDictionary { + [key: string]: T; +} + +export interface IHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} + +/** Boom Module for errors. https://github.com/hapijs/boom + * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ +export interface IBoom extends Error { + /** if true, indicates this is a Boom object instance. */ + isBoom: boolean; + /** convenience bool indicating status code >= 500. */ + isServer: boolean; + /** the error message. */ + message: string; + /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ + output: { + /** the HTTP status code (typically 4xx or 5xx). */ + statusCode: number; + /** an object containing any HTTP headers where each key is a header name and value is the header content. */ + headers: IDictionary; + /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ + payload: { + /** the HTTP status code, derived from error.output.statusCode. */ + statusCode: number; + /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ + error: string; + /** the error message derived from error.message. */ + message: string; + }; + }; + /** reformat()rebuilds error.output using the other object properties. */ + reformat(): void; +} + +/** cache functionality via the "CatBox" module. */ +export interface ICatBoxCacheOptions { + /** a prototype function or catbox engine object. */ + engine: any; + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ + name?: string; + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; +} + +/** policy configuration for the "CatBox" module and server method options. */ +export interface ICatBoxCachePolicyOptions { + /** the cache name configured in server.cache. Defaults to the default cache. */ + cache?: string; + /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ + segment?: string; + /** if true, allows multiple cache provisions to share the same segment. Default to false. */ + shared?: boolean; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. */ + expiresAt?: number; + /** a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. */ + generateFunc?: Function; + /** number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. */ + staleIn?: number; + /** number of milliseconds to wait before checking if an item is stale. */ + staleTimeout?: number; + /** number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + generateTimeout?: number; + /** if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true */ + dropOnError?: boolean; + /** if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */ + generateOnReadError?: boolean; + /** if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. */ + generateIgnoreWriteError?: boolean; + /** number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). */ + pendingGenerateTimeout?: number; +} + +/** Any connections configuration server defaults can be included to override and customize the individual connection. */ +export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ + host?: string; + /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ + address?: string; + /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ + port?: string | number; + /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ + uri?: string; + /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ + listener?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ + statuses: number[]; + }; + /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ + labels?: string | string[]; + /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; +} + +export interface IConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** if false, response content encoding is disabled. Defaults to true */ + compression?: boolean; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: IRouteAdditionalConfigurationOptions; + state?: IServerState; +} + +/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ +export interface IServerOptions { + /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). + a configuration object with the following options: + enginea prototype function or catbox engine object. + namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. + sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + other options passed to the catbox strategy used. + an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ + cache?: string | ICatBoxCacheOptions | ICatBoxCacheOptions[] | any; + /** sets the default connections configuration which can be overridden by each connection where: */ + connections?: IConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ + debug?: boolean | { + /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log: string[]; + /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ + request: string[]; + }; + /** file system related settings*/ + files?: { + /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ + etagsCacheMaxSize?: number; + }; + /** process load monitoring*/ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ + sampleInterval?: number; + }; + + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ + mime?: any; + /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ + minimal?: boolean; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ + plugins?: IDictionary; +} + +export interface IServerViewCompile { + (template: string, options: any): void; + (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; +} + +export interface IServerViewsAdditionalOptions { + /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ + path?: string; + /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + */ + partialsPath?: string; + /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ + helpersPath?: string; + /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ + relativeTo?: string; + + /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ + layout?: boolean | string; + /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ + layoutPath?: string; + /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ + layoutKeywork?: string; + /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ + encoding?: string; + /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ + isCached?: boolean; + /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ + allowAbsolutePaths?: boolean; + /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ + allowInsecureAccess?: boolean; + /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ + compileOptions?: any; + /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ + runtimeOptions?: any; + /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ + contentType?: string; + /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ + compileMode?: string; + /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ + context?: any; +} + +export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { + /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. + * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ + module: { + compile?(template: any, options: any): (context: any, options: any) => void; + compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + }; +} + +/**Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + + server.views({ +engines: { +html: require('handlebars'), +jade: require('jade') +}, +path: '/static/templates' +}); + When server.views() is called within a plugin, the views manager is only available to plugins methods. + */ +export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { + /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ + engines: IDictionary | IServerViewsEnginesOptions; + /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ + defaultExtension?: string; +} + +export interface IReplyMethods { + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + * The data argument is only used for passing back authentication data and is ignored elsewhere. */ + continue(credentialData?: any): void; + + /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ + file(/** the file path. */ + path: string, + /** optional settings: */ + options?: { + /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /** specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed: boolean; + }): void; + /** Concludes the handler activity by returning control over to the router with a templatized view response. + the response flow control rules apply. */ + view(/** the template filename and path, relative to the templates path configured via the server views manager. */ + template: string, + /** optional object used by the template to render context-specific result. Defaults to no context {}. */ + context?: {}, + /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ + options?: any): Response; + /** Sets a header on the response */ + header(name: string, value: string, options?: IHeaderOptions): Response; + + /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed + The response flow control rules do not apply. */ + close(options?: { + /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ + end?: boolean; + }): void; + /** Proxies the request to an upstream endpoint. + the response flow control rules do not apply. */ + + proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ + options: IProxyHandlerConfig): void; + /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). + he response flow control rules apply. */ + redirect(uri: string): ResponseRedirect; + + /** Replies with the specified response */ + response(result: any): Response; + + /** Sets a cookie on the response */ + state(name: string, value: any, options?: any): void; + + /** Clears a cookie on the response */ + unstate(name: string, options?: any): void; +} + +/** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ +export interface IReply extends IReplyMethods { + ( + err: Error, + result?: string | number | boolean | Buffer | stream.Stream | Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string | number | boolean | Buffer | stream.Stream | Promise | T): Response; +} + +/** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ +export interface IStrictReply extends IReplyMethods { + (err: Error, + result?: Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: Promise | T): Response; +} + +export interface ISessionHandler { + (request: Request, reply: IReply): void; +} + +export interface IStrictSessionHandler { + (request: Request, reply: IStrictReply): void; +} + +export interface IRequestHandler { + (request: Request): T; +} + +export interface IFailAction { + (source: string, error: any, next: () => void): void; +} +/** generates a reverse proxy handler */ +export interface IProxyHandlerConfig { + /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ + host?: string; + /** the upstream service port. */ + port?: number; + /** The protocol to use when making a request to the proxied host: + 'http' + 'https'*/ + protocol?: string; + /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ + uri?: string; + /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ + passThrough?: boolean; + /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ + localStatePassThrough?: boolean; + /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ + rejectUnauthorized?: boolean; + /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ + xforward?: boolean; + /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ + redirects?: boolean | number; + /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ + timeout?: number; + /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: + request - is the incoming request object. + callback - is function(err, uri, headers) where: + err - internal error condition. + uri - the absolute proxy URI. + headers - optional object where each key is an HTTP request header and the value is the header content.*/ + mapUri?(request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void): void; + /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ + onResponse?( + err: any, + res: http.ServerResponse, + req: Request, + reply: IReply, + settings: IProxyHandlerConfig, + ttl: number): void; + /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ + ttl?: number; + /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ + agent?: http.Agent; + /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ + maxSockets?: boolean | number; +} +/** TODO: fill in joi definition */ +export interface IJoi { } + +/** a validation function using the signature function(value, options, next) */ +export interface IValidationFunction { + ( + /** the object containing the path parameters. */ + value: any, + /** the server validation options. */ + options: any, + /** the callback function called when validation is completed. */ + next: (err: any, value: any) => void): void; +} +/** a custom error handler function with the signature 'function(request, reply, source, error)` */ +export interface IRouteFailFunction { + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + (/** - the [request object]. */ + request: Request, + /** the continuation reply interface. */ + reply: IReply, + /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ + source: string, + /** the error object prepared for the client response (including the validation function error under error.data). */ + error: any): void; +} + +/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ +export interface IRouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. + a string with the name of an authentication strategy registered with server.auth.strategy(). + an object */ + auth?: boolean | string | + { + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + 'required'authentication is required. + 'optional'authentication is optional (must be valid if present). + 'try'same as 'optional' but allows for invalid authentication. */ + mode?: string; + /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies?: string | string[]; + /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: + falseno payload authentication.This is the default value. + 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. + 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ + payload?: string; + /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ + scope?: string | string[] | boolean; + /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: + anythe authentication can be on behalf of a user or application.This is the default value. + userthe authentication must be on behalf of a user. + appthe authentication must be on behalf of an application. */ + entity?: string; + /** + * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming + * request and access is granted if at least one rule matches. Each rule object must include at least one of: + */ + access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; + }; + /** an object passed back to the provided handler (via this) when called. */ + bind?: any; + /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ + cache?: IRouteAdditionalConfigurationCache; + /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ + cors?: { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ + origin?: string[]; + /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ + matchOrigin?: boolean; + /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ + isOriginExposed?: boolean; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ + headers?: string[]; + /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ + methods?: string[]; + /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ + additionalMethods?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ + credentials?: boolean; + /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ + override?: boolean; + }; + /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ + files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ + relativeTo: string; + }; + + /** an alternative location for the route handler option. */ + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + /** an optional unique identifier used to look up the route using server.lookup(). */ + id?: number; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ + json?: { + /** the replacer function or array.Defaults to no action. */ + replacer?: Function | string[]; + /** number of spaces to indent nested object keys.Defaults to no indentation. */ + space?: number | string; + /** string suffix added after conversion to JSON string.Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ + jsonp?: string; + /** determines how the request payload is processed: */ + payload?: { + /** the type of payload representation requested. The value must be one of: + 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. + 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ + output?: string; + /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + 'application/json' + 'application/x-www-form-urlencoded' + 'application/octet-stream' + 'text/ *' + 'multipart/form-data' */ + parse?: string | boolean; + /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ + uploads?: string; + /** determines how to handle payload parsing errors. Allowed values are: + 'error'return a Bad Request (400) error response. This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action and continue processing the request. */ + failAction?: string; + }; + /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: IDictionary; + /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ + pre?: any[]; + /** validation rules for the outgoing response payload (response body).Can only validate object response: */ + response?: { + /** the default HTTP status code when the payload is empty. Value can be 200 or 204. + Note that a 200 status code is converted to a 204 only at the time or response transmission + (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ + emptyStatusCode?: number; + /** the default response object validation rules (for all non-error responses) expressed as one of: + true - any payload allowed (no validation performed). This is the default. + false - no payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + value - the object containing the response object. + options - the server validation options. + next(err) - the callback function called when validation is completed. */ + schema?: boolean | any; + /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ + status?: { [statusCode: number]: boolean | any }; + /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ + sample?: number; + /** defines what to do when a response fails validation.Options are: + errorreturn an Internal Server Error (500) error response.This is the default value. + loglog the error but send the response. */ + failAction?: string; + /** if true, applies the validation rule changes to the response.Defaults to false. */ + modify?: boolean; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ + security?: boolean | { + /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ + hsts?: boolean | number | { + /** the max- age portion of the header, as a number.Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubdomains flag to the header. */ + includeSubdomains?: boolean; + /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ + preload?: boolean; + }; + /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe?: { + /** either 'deny', 'sameorigin', or 'allow-from' */ + rule: string; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ + xss?: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ + noOpen?: boolean; + /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ + noSniff?: boolean; + }; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ + parse: boolean; + /** determines how to handle cookie parsing errors.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action. */ + failAction: string; + }; + /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ + validate?: { + /** validation rules for incoming request headers.Values allowed: + * trueany headers allowed (no validation performed).This is the default. + falseno headers allowed (this will cause all valid HTTP requests to fail). + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the request headers. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. + */ + headers?: boolean | IJoi | IValidationFunction; + + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: + trueany path parameters allowed (no validation performed).This is the default. + falseno path variables allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the path parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + params?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: + trueany query parameters allowed (no validation performed).This is the default. + falseno query parameters allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the query parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + query?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request payload (request body).Values allowed: + trueany payload allowed (no validation performed).This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the payload object. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + payload?: boolean | IJoi | IValidationFunction; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** determines how to handle invalid requests.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'log the error but continue processing the request. + 'ignore'take no action. + OR a custom error handler function with the signature 'function(request, reply, source, error)` where: + requestthe request object. + replythe continuation reply interface. + sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). + errorthe error object prepared for the client response (including the validation function error under error.data). */ + failAction?: string | IRouteFailFunction; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ + server: boolean | number; + /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ + socket: boolean | number; + }; + + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route description used for generating documentation (string). + */ + description?: string; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route notes used for generating documentation (string or array of strings). + */ + notes?: string | string[]; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route tags used for generating documentation (array of strings). + */ + tags?: string[]; + + /** Enable logging of routes + */ + log?: boolean; +} + +/** + * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches + */ +export interface IRouteAdditionalConfigurationAuthAccess { + /** + * the application scope required to access the route. Value can be a scope string or an array of scope strings. + * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, + * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' + * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties + * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, + * such as 'user-{params.id}'. Defaults to false (no scope requirements). + */ + scope?: string | string[] | boolean; + /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: + * any - the authentication can be on behalf of a user or application. This is the default value. + * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. + * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + */ + entity?: string; +} + +export type IRouteAdditionalConfigurationCache = { + /** determines the privacy flag included in clientside caching using the 'Cache-Control' header. Values are: + 'Default': no privacy flag.This is the default setting. + 'public': mark the response as suitable for public caching. + 'private': mark the response as suitable only for private caching. */ + privacy?: 'default' | 'public' | 'private'; + /** an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive. Defaults to [200]. */ + statuses?: number[]; + /** a string with the value of the 'Cache-Control' header when caching is disabled. Defaults to 'no-cache'. */ + otherwise?: string; +} & ({ + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn: number; +} | { + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt: string; +} | {}); + +/** server.realm http://hapijs.com/api#serverrealm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { +console.log(server.realm.modifiers.route.prefix); +return next(); +}; + */ +export interface IServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ + modifiers: { + /** routes preferences: */ + route: { + /** - the route path prefix used by any calls to server.route() from the server. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + }; + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: IDictionary; + /** settings overrides */ + settings: { + files: { + relativeTo: any; + }; + bind: any; + }; +} +/** server.state(name, [options]) http://hapijs.com/api#serverstatename-options + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ +export interface IServerState { + /** - the cookie name string. */ + name: string; + + /** - are the optional cookie settings: */ + options: { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly: boolean + /** - the path scope.Defaults to null (no path).*/ + path: any; + /** - the domain scope.Defaults to null (no domain). */ + domain: any; + /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue(request: Request, next: (err: any, value: any) => void): void; + /** - encoding performs on the provided value before serialization. Options are: + 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON-stringified than encoded using Base64. + 'form' - object value is encoded using the x-www-form-urlencoded method. + 'iron' - Encrypts and sign the value using iron.*/ + encoding: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/ + sign: { + /** - algorithm options.Defaults to require('iron').defaults.integrity.*/ + integrity: any; + /** - password used for HMAC key generation.*/ + password: string; + }; + /** - password used for 'iron' encoding.*/ + password: string; + /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/ + iron: any; + /** - if false, errors are ignored and treated as missing cookies.*/ + ignoreErrors: boolean; + /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/ + clearInvalid: boolean; + /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/ + strictHeader: boolean; + /** - overrides the default proxy localStatePassThrough setting.*/ + passThrough: any; + }; +} + +export interface IFileHandlerConfig { + /** a path string or function as described above.*/ + path: string; + /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean | string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ + lookupCompressed: boolean; +} + +/**http://hapijs.com/api#route-handler + Built-in handlers + + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ +export interface IRouteHandlerConfig { + /** generates a static file endpoint for serving a single file. file can be set to: + a relative or absolute file path string (relative paths are resolved based on the route files configuration). + a function with the signature function(request) which returns the relative or absolute file path. + an object with the following options */ + file?: string | IRequestHandler | IFileHandlerConfig; + /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. + listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. + defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ + directory?: { + path: string | string[] | IRequestHandler | IRequestHandler; + index?: boolean | string | string[]; + listing?: boolean; + showHidden?: boolean; + redirectToSlash?: boolean; + lookupCompressed?: boolean; + defaultExtension?: string; + }; + proxy?: IProxyHandlerConfig; + view?: string | { + template: string; + context: { + payload: any; + params: any; + query: any; + pre: any; + } + }; + config?: { + handler: any; + bind: any; + app: any; + plugins: { + [name: string]: any; + }; + pre: Array<() => void>; + validate: { + headers: any; + params: any; + query: any; + payload: any; + errorFields?: any; + failAction?: string | IFailAction; + }; + payload: { + output: { + data: any; + stream: any; + file: any; + }; + parse?: any; + allow?: string | string[]; + override?: string; + maxBytes?: number; + uploads?: number; + failAction?: string; + }; + response: { + schema: any; + sample: number; + failAction: string; + }; + cache: { + privacy: string; + expiresIn: number; + expiresAt: number; + }; + auth: string | boolean | { + mode: string; + strategies: string[]; + payload?: boolean | string; + tos?: boolean | string; + scope?: string | string[]; + entity: string; + }; + cors?: boolean; + jsonp?: string; + description?: string; + notes?: string | string[]; + tags?: string[]; + }; +} +/** Route configuration + The route configuration object*/ +export interface IRouteConfiguration { + /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ + path: string; + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ + method: string | string[]; + /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ + vhost?: string; + /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + /** - additional route options.*/ + config?: IRouteAdditionalConfigurationOptions; +} +/** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ +export interface IRoute { + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | string[]; + /** the [active realm] associated with the route.*/ + realm: IServerRealm; + /** the [route options] object with all defaults applied. */ + settings: IRouteAdditionalConfigurationOptions; +} + +export interface IServerAuthScheme { + /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: + request - the request object. + reply - the reply interface the authentication method must call when done authenticating the request where: + reply(err, response, result) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + result - an object containing: + credentials - the authenticated credentials. + artifacts - optional authentication artifacts. + reply.continue(result) - is called if authentication succeeded where: + result - same object as result above. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var scheme = function (server, options) { + return { + authenticate: function (request, reply) { + var req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply(null, { credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme);*/ + authenticate(request: Request, reply: IReply): void; + authenticate(request: Request, reply: IStrictReply): void; + /** payload(request, reply) - optional function called to authenticate the request payload where: + request - the request object. + reply(err, response) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + reply.continue() - is called if payload authentication succeeded. + When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ + payload?(request: Request, reply: IReply): void; + payload?(request: Request, reply: IStrictReply): void; + /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: + request - the request object. + reply(err, response) - is called if an error occurred where: + err - any authentication error. + response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + reply.continue() - is called if the operation succeeded.*/ + response?(request: Request, reply: IReply): void; + response?(request: Request, reply: IStrictReply): void; + /** an optional object */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ + payload: boolean; + }; +} + +/**the response object where: + statusCode - the HTTP status code. + headers - an object containing the headers set. + payload - the response payload string. + rawPayload - the raw response payload buffer. + raw - an object with the injection request and response objects: + req - the simulated node request object. + res - the simulated node response object. + result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + request - the request object.*/ +export interface IServerInjectResponse { + statusCode: number; + headers: IDictionary; + payload: string; + rawPayload: Buffer; + raw: { + req: http.IncomingMessage; + res: http.ServerResponse + }; + result: any; + request: Request; +} + +export interface IServerInject { + (options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void; + (options: string | IServerInjectOptions): Promise; +} + +export interface IServerInjectOptions { + /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ + method: string; + /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ + url: string; + /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ + headers?: IDictionary; + /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ + payload?: string | {} | Buffer; + /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ + credentials?: any; + /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ + artifacts?: any; + /** sets the initial value of request.app*/ + app?: any; + /** sets the initial value of request.plugins*/ + plugins?: any; + /** allows access to routes with config.isInternal set to true. Defaults to false.*/ + allowInternals?: boolean; + /** sets the remote address for the incoming connection.*/ + remoteAddress?: boolean; + /**object with options used to simulate client request stream conditions for testing: + error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + end - if false, does not end the stream. Defaults to true.*/ + simulate?: { + error: boolean; + close: boolean; + end: boolean; + }; +} + +/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path.*/ +export interface IConnectionTable { + info: any; + labels: any; + table: IRoute[]; +} + +export interface ICookieSettings { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl?: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure?: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly?: boolean; + /** - the path scope.Defaults to null (no path).*/ + path?: string; + /** - the domain scope.Defaults to null (no domain).*/ + domain?: any; + /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue?(request: Request, next: (err: any, value: any) => void): void; + /** - encoding performs on the provided value before serialization.Options are: + 'none' - no encoding.When used, the cookie value must be a string.This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON- stringified than encoded using Base64. + 'form' - object value is encoded using the x- www - form - urlencoded method. */ + encoding?: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: + integrity - algorithm options.Defaults to require('iron').defaults.integrity. + password - password used for HMAC key generation. */ + sign?: { integrity: any; password: string; }; + password?: string; + iron?: any; + ignoreErrors?: boolean; + clearInvalid?: boolean; + strictHeader?: boolean; + passThrough?: any; +} + +/** method - the method function with the signature is one of: + function(arg1, arg2, ..., argn, next) where: + arg1, arg2, etc. - the method function arguments. + next - the function called when the method is done with the signature function(err, result, ttl) where: + err - error response if the method failed. + result - the return value. + ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + function(arg1, arg2, ..., argn) where: + arg1, arg2, etc. - the method function arguments. + the callback option is set to false. + the method must returns a value (result, Error, or a promise) or throw an Error.*/ +export interface IServerMethod { + // (): void; + // (next: (err: any, result: any, ttl: number) => void): void; + // (arg1: any): void; + // (arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; + // (arg1: any, arg2: any): void; + (...args: any[]): void; +} +/** options - optional configuration: + bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. + cache - the same cache configuration used in server.cache(). + callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ +export interface IServerMethodOptions { + bind?: any; + cache?: ICatBoxCachePolicyOptions; + callback?: boolean; + generateKey?(args: any[]): string; +} +/** Request object + + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + Request events + + The request object supports the following events: + + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the request payload finished reading. The event method signature is function (). + 'disconnect' - emitted when a request errors or aborts unexpectedly. + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + +var hash = Crypto.createHash('sha1'); +request.on('peek', function (chunk) { + +hash.update(chunk); +}); + +request.once('finish', function () { + +console.log(hash.digest('hex')); +}); + +request.once('disconnect', function () { + +console.error('request aborted'); +}); + +return reply.continue(); +});*/ +export class Request extends Events.EventEmitter { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** authentication information*/ + auth: { + /** true is the request has been successfully authenticated, otherwise false.*/ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ + artifacts: any; + /** the route authentication mode.*/ + mode: any; + /** the authentication error is failed and mode set to 'try'.*/ + error: any; + }; + /** the connection used by this request*/ + connection: ServerConnection; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ + domain: any; + /** the raw request headers (references request.raw.headers).*/ + headers: IDictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: string; + /** request information */ + info: { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com').*/ + hostname: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: number; + /** request response timestamp (0 is not responded yet). */ + responded: number; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ + params: IDictionary; + /** an array containing all the path params values in the order they appeared in the path.*/ + paramsArray: string[]; + /** the request URI's path component. */ + path: string; + /** the request payload based on the route payload.output and payload.parse settings.*/ + payload: stream.Readable | Buffer | any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ + plugins: any; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ + pre: IDictionary; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ + response: Response; + /**preResponses - same as pre but represented as the response object created by the pre method.*/ + preResponses: any; + /**an object containing the query parameters.*/ + query: any; + /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ + raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + /** the route public interface.*/ + route: IRoute; + /** the server object. */ + server: Server; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: any; + /** complex object contining details on the url */ + url: { + /** null when i tested */ + auth: any; + /** null when i tested */ + hash: any; + /** null when i tested */ + host: any; + /** null when i tested */ + hostname: any; + href: string; + path: string; + /** path without search*/ + pathname: string; + /** null when i tested */ + port: any; + /** null when i tested */ + protocol: any; + /** querystring parameters*/ + query: IDictionary; + /** querystring parameters as a string*/ + search: string; + /** null when i tested */ + slashes: any; + }; + + /** request.setUrl(url) + + Available only in 'onRequest' extension methods. + + Changes the request URI before the router begins processing the request where: + + url - the new request path value. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + });*/ + setUrl(url: string | url.Url): void; + /** request.setMethod(method) + + Available only in 'onRequest' extension methods. + + Changes the request method before the router begins processing the request where: + + method - is the request HTTP method (e.g. 'GET'). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); + });*/ + setMethod(method: string): void; + + /** request.log(tags, [data, [timestamp]]) + + Always available. + + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.on('request', function (request, event, tags) { + + if (tags.error) { + console.log(event); + } + }); + + var handler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); + }; + */ + log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ + tags: string | string[], + /** an optional message string or object with the application data being logged.*/ + data?: any, + /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ + timestamp?: number): void; + + /** request.getLog([tags], [internal]) + + Always available. + + Returns an array containing the events matching any of the tags specified (logical OR) + request.getLog(); + request.getLog('error'); + request.getLog(['error', 'auth']); + request.getLog(['error'], true); + request.getLog(false);*/ + + getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ + tags?: string, + /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ + internal?: boolean): string[]; + + /** request.tail([name]) + + Available until immediately after the 'response' event is emitted. + + Adds a request tail which has to complete before the request lifecycle is complete where: + + name - an optional tail name used for logging purposes. + Returns a tail function which must be called when the tail activity is completed. + + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + + When all tails completed, the server emits a 'tail' event. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + var get = function (request, reply) { + + var dbTail = request.tail('write to database'); + + db.save('key', 'value', function () { + + dbTail(); + }); + + return reply('Success!'); + }; + + server.route({ method: 'GET', path: '/', handler: get }); + + server.on('tail', function (request) { + + console.log('Request completed including db activity'); + });*/ + tail(/** an optional tail name used for logging purposes.*/ + name?: string): Function; +} +/** Response events + + The response object supports the following events: + + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onPreResponse', function (request, reply) { + +var response = request.response; +if (response.isBoom) { +return reply(); +} + +var hash = Crypto.createHash('sha1'); +response.on('peek', function (chunk) { + +hash.update(chunk); +}); + +response.once('finish', function () { + +console.log(hash.digest('hex')); +}); + +return reply.continue(); +});*/ +export class Response extends Events.EventEmitter { + isBoom: boolean; + /** the HTTP response status code. Defaults to 200 (except for errors).*/ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ + headers: IDictionary; + /** the value provided using the reply interface.*/ + source: any; + /** a string indicating the type of source with available values: + 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + 'buffer' - a Buffer. + 'view' - a view generated with reply.view(). + 'file' - a file generated with reply.file() of via the directory handler. + 'stream' - a Stream. + 'promise' - a Promise object. */ + variety: string; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: any; + /** settings - response handling flags: + charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. + encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. + passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. + stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. + ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. + varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ + settings: { + charset: string; + encoding: string; + passThrough: boolean; + stringify: any; + ttl: number; + varyEtag: boolean; + }; + + /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + length - the header value. Must match the actual payload size.*/ + bytes(length: number): Response; + + /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ + charset(charset: string): Response; + + /** sets the HTTP status code where: + statusCode - the HTTP status code.*/ + code(statusCode: number): Response; + + /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ + created(uri: string): Response; + + /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ + encoding(encoding: string): Response; + + /** etag(tag, options) - sets the representation entity tag where: + tag - the entity tag string without the double-quote. + options - optional settings where: + weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ + etag(tag: string, options: { + weak: boolean; vary: boolean; + }): Response; + + /**header(name, value, options) - sets an HTTP header where: + name - the header name. + value - the header value. + options - optional settings where: + append - if true, the value is appended to any existing header value using separator. Defaults to false. + separator - string used as separator when appending to an exiting value. Defaults to ','. + override - if false, the header value is not set if an existing value present. Defaults to true.*/ + header(name: string, value: string, options?: IHeaderOptions): Response; + + /** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */ + hold(): Response; + + /** location(uri) - sets the HTTP 'Location' header where: + uri - an absolute or relative URI used as the 'Location' header value.*/ + location(uri: string): Response; + + /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: + uri - an absolute or relative URI used to redirect the client to another resource. */ + redirect(uri: string): Response; + + /** replacer(method) - sets the JSON.stringify() replacer argument where: + method - the replacer function or array. Defaults to none.*/ + replacer(method: Function | Function[]): Response; + + /** spaces(count) - sets the JSON.stringify() space argument where: + count - the number of spaces to indent nested object keys. Defaults to no indentation. */ + spaces(count: number): Response; + + /**state(name, value, [options]) - sets an HTTP cookie where: + name - the cookie name. + value - the cookie value. If no encoding is defined, must be a string. + options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + state(name: string, value: string, options?: any): Response; + + /** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */ + send(): void; + + /** sets a string suffix when the response is process via JSON.stringify().*/ + suffix(suffix: string): void; + + /** overrides the default route cache expiration rule for this response instance where: + msec - the time-to-live value in milliseconds.*/ + ttl(msec: number): void; + + /** type(mimeType) - sets the HTTP 'Content-Type' header where: + mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ + type(mimeType: string): Response; + + /** clears the HTTP cookie by setting an expired value where: + name - the cookie name. + options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + unstate(name: string, options?: { [key: string]: string }): Response; + + /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + header - the HTTP request header name.*/ + vary(header: string): void; +} +/** When using the redirect() method, the response object provides these additional methods */ +export class ResponseRedirect extends Response { + /** sets the status code to 302 or 307 (based on the rewritable() setting) where: + isTemporary - if false, sets status to permanent. Defaults to true.*/ + temporary(isTemporary: boolean): void; + + /** sets the status code to 301 or 308 (based on the rewritable() setting) where: + isPermanent - if true, sets status to temporary. Defaults to false. */ + permanent(isPermanent: boolean): void; + + /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: + isRewritable - if false, sets to non-rewritable. Defaults to true. + Permanent Temporary + Rewritable 301 302(1) + Non-rewritable 308(2) 307 + Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ + rewritable(isRewritable: boolean): void; +} +/** info about a server connection */ +export interface IServerConnectionInfo { + /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ + id: string; + /** - the connection creation timestamp.*/ + created: number; + /** - the connection start timestamp (0 when stopped).*/ + started: number; + /** the connection port based on the following rules: + the configured port value before the server has been started. + the actual port assigned when no port is configured or set to 0 after the server has been started.*/ + port: number; + + /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ + host: string; + /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ + address: string; + /** - the protocol used: + 'http' - HTTP. + 'https' - HTTPS. + 'socket' - UNIX domain socket or Windows named pipe.*/ + protocol: string; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ + uri: string; +} +/** + * undocumented. The connection object constructed after calling server.connection(); + * can be accessed via server.connections; or request.connection; + */ +export class ServerConnection extends Events.EventEmitter { + domain: any; + _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; + _eventsCount: number; + settings: IServerConnectionOptions; + server: Server; + /** ex: "tcp" */ + type: string; + _started: boolean; + /** dictionary of sockets */ + _connections: { [ip_port: string]: any }; + _onConnection: Function; + registrations: any; + _extensions: any; + _requestCounter: { value: number; min: number; max: number }; + _load: any; + states: { + settings: any; cookies: any; names: any[] + }; + auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; }; + _router: any; + MSPluginsCollection: any; + applicationCache: any; + addEventListener: any; + info: IServerConnectionInfo; +} + +export type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; +export type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; + +/** Server http://hapijs.com/api#server + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + Server events + The server object inherits from Events.EventEmitter and emits the following events: + 'log' - events logged with server.log() and server events generated internally by the framework. + 'start' - emitted when the server is started using server.start(). + 'stop' - emitted when the server is stopped using server.stop(). + 'request' - events generated by request.log(). Does not include any internally generated events. + 'request-internal' - request events generated internally by the framework (multiple events per request). + 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. + 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. + 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. + Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. + MORE EVENTS HERE: http://hapijs.com/api#server-events*/ +export class Server extends Events.EventEmitter { + constructor(options?: IServerOptions); + + /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + var Hapi = require('hapi'); + server = new Hapi.Server(); + server.app.key = 'value'; + var handler = function (request, reply) { + return reply(request.server.app.key); + }; */ + app: any; + /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + var server = new Hapi.Server(); + server.connection({ port: 80, labels: 'a' }); + server.connection({ port: 8080, labels: 'b' }); + // server.connections.length === 2 + var a = server.select('a'); + // a.connections.length === 1*/ + connections: ServerConnection[]; + /** When the server contains exactly one connection, info is an object containing information about the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // server.info.port === 80 + server.connection({ port: 8080 }); + // server.info === null + // server.connections[1].info.port === 8080 + */ + info: IServerConnectionInfo; + /** An object containing the process load metrics (when load.sampleInterval is enabled): + rss - RSS memory usage. + var Hapi = require('hapi'); + var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + console.log(server.load.rss);*/ + load: { + /** - event loop delay milliseconds.*/ + eventLoopDelay: number; + /** - V8 heap usage.*/ + heapUsed: number; + }; + /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + When the server contains more than one connection, each server.connections array member provides its own connection.listener. + var Hapi = require('hapi'); + var SocketIO = require('socket.io'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var io = SocketIO.listen(server.listener); + io.sockets.on('connection', function(socket) { + socket.emit({ msg: 'welcome' }); + });*/ + listener: http.Server; + + /** server.methods + An object providing access to the server methods where each server method name is an object property. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.method('add', function (a, b, next) { + return next(null, a + b); + }); + server.methods.add(1, 2, function (err, result) { + // result === 3 + });*/ + methods: IDictionary; + + /** server.mime + Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + var Hapi = require('hapi'); + var options = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } + }; + var server = new Hapi.Server(options); + // server.mime.path('code.js').type === 'application/javascript' + // server.mime.path('file.npm').type === 'node/module'*/ + mime: any; + /**server.plugins + An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + exports.register = function (server, options, next) { + server.expose('key', 'value'); + // server.plugins.example.key === 'value' + return next(); + }; + exports.register.attributes = { + name: 'example' + };*/ + plugins: IDictionary; + /** server.realm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: + route - routes preferences: + prefix - the route path prefix used by any calls to server.route() from the server. + vhost - the route virtual host settings used by any calls to server.route() from the server. + plugin - the active plugin name (empty string if at the server root). + plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. + settings - settings overrides: + files.relativeTo + bind + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + };*/ + realm: IServerRealm; + + /** server.root + The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ + root: Server; + /** server.settings + The server configuration object after defaults applied. + var Hapi = require('hapi'); + var server = new Hapi.Server({ + app: { + key: 'value' + } + }); + // server.settings.app === { key: 'value' }*/ + settings: IServerOptions; + + /** server.version + The hapi module version number. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + // server.version === '8.0.0'*/ + version: string; + + /** server.after(method, [dependencies]) + Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: + after - the method with signature function(plugin, next) where: + server - server object the after() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error which is returned back via the server.start() callback. + dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.after(function () { + // Perform some pre-start logic + }); + server.start(function (err) { + // After method already executed + }); + server.auth.default(options)*/ + after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; + + auth: { + /** server.auth.api + An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. + When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. + const server = new Hapi.Server(); + server.connection({ port: 80 }); + const scheme = function (server, options) { + return { + api: { + settings: { + x: 5 + } + }, + authenticate: function (request, reply) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply.continue({ credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + console.log(server.auth.api.default.settings.x); // 5 + */ + api: { + [index: string]: any; + } + /** server.auth.default(options) + Sets a default strategy which is applied to every route where: + options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. + The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. + The default auth strategy configuration can be accessed via connection.auth.settings.default. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + });*/ + default(options: string): void; + default(options: { strategy: string }): void; + default(options: { strategies: string[] }): void; + /** server.auth.scheme(name, scheme) + Registers an authentication scheme where: + name - the scheme name. + scheme - the method implementing the scheme with signature function(server, options) where: + server - a reference to the server object the scheme is added to. + options - optional scheme settings used to instantiate a strategy.*/ + scheme( + name: string, + /** + * When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + * n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * server = new Hapi.Server(); + * server.connection({ port: 80 }); + * scheme = function (server, options) { + * urn { + * authenticate: function (request, reply) { + * req = request.raw.req; + * var authorization = req.headers.authorization; + * if (!authorization) { + * return reply(Boom.unauthorized(null, 'Custom')); + * } + * urn reply(null, { credentials: { user: 'john' } }); + * } + * }; + * }; + */ + scheme: (server: Server, options: any) => IServerAuthScheme): void; + + /** + * server.auth.strategy(name, scheme, [mode], [options]) + * Registers an authentication strategy where: + * name - the strategy name. + * scheme - the scheme name (must be previously registered using server.auth.scheme()). + * mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. + * options - scheme options based on the scheme requirements. + * var server = new Hapi.Server(); + * server.connection({ port: 80 }); + * server.auth.scheme('custom', scheme); + * server.auth.strategy('default', 'custom'); + * server.route({ + * method: 'GET', + * path: '/', + * config: { + * auth: 'default', + * handler: function (request, reply) { + * return reply(request.auth.credentials.user); + * } + * } + * }); + */ + strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string): void; + strategy(name: string, scheme: string, options?: any): void; + + /** server.auth.test(strategy, request, next) + Tests a request against an authentication strategy where: + strategy - the strategy name registered with server.auth.strategy(). + request - the request object. + next - the callback function with signature function(err, credentials) where: + err - the error if authentication failed. + credentials - the authentication credentials object if authentication was successful. + Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.server.auth.test('default', request, function (err, credentials) { + if (err) { + return reply({ status: false }); + } + return reply({ status: true, user: credentials.name }); + }); + } + });*/ + test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; + }; + + /** server.bind(context) + Sets a global context used as the default bind object when adding a route or an extension where: + context - the object used to bind this in handler and extension methods. + When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + var handler = function (request, reply) { + return reply(this.message); + }; + exports.register = function (server, options, next) { + var bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); + };*/ + bind(context: any): void; + + /** server.cache(options) + Provisions a cache segment within the server cache facility where: + options - catbox policy configuration where: + expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + staleTimeout - number of milliseconds to wait before checking if an item is stale. + generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. + cache - the cache name configured in 'server.cache`. Defaults to the default cache. + segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. + shared - if true, allows multiple cache provisions to share the same segment. Default to false. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, function (err) { + cache.get('norway', function (err, value, cached, log) { + // value === { capital: 'oslo' }; + }); + });*/ + cache(options: ICatBoxCachePolicyOptions): void; + + /** server.connection([options]) + Adds an incoming server connection + Returns a server object with the new connection selected. + Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). + Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); + var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + // server.connections.length === 2 + // web.connections.length === 1 + // admin.connections.length === 1 */ + connection(options: IServerConnectionOptions): Server; + + /** server.decorate(type, property, method, [options]) + Extends various framework interfaces with custom methods where: + type - the interface being decorated. Supported types: + 'reply' - adds methods to the reply interface. + 'server' - adds methods to the Server object. + property - the object decoration key name. + method - the extension function. + options - if the type is 'request', supports the following optional settings: + 'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + Note that decorations apply to the entire server and all its connections regardless of current selection. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.decorate('reply', 'success', function () { + return this.response({ status: 'ok' }); + }); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply.success(); + } + });*/ + decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void; + + /** server.dependency(dependencies, [after]) + Used within a plugin to declares a required dependency on other plugins where: + dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. + after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + server - the server the dependency() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error condition, which is returned back via the server.start() callback. + exports.register = function (server, options, next) { + server.dependency('yar', after); + return next(); + }; + var after = function (server, next) { + // Additional plugin registration logic + return next(); + };*/ + dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; + + /** server.expose(key, value) + Used within a plugin to expose a property via server.plugins[name] where: + key - the key assigned (server.plugins[name][key]). + value - the value assigned. + exports.register = function (server, options, next) { + server.expose('util', function () { console.log('something'); }); + return next(); + };*/ + expose(key: string, value: any): void; + + /** server.expose(obj) + Merges a deep copy of an object into to the existing content of server.plugins[name] where: + obj - the object merged into the exposed properties container. + exports.register = function (server, options, next) { + server.expose({ util: function () { console.log('something'); } }); + return next(); + };*/ + expose(obj: any): void; + + /** server.ext(event, method, [options]) + Registers an extension function in one of the available extension points where: + event - the event name. + method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: + request - the request object. NOTE: Access the Response via request.response + reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + this - the object provided via options.bind or the current active context set with server.bind(). + options - an optional object with the following: + before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + bind - a context object passed back to the provided method (via this) when called. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + }); + var handler = function (request, reply) { + return reply({ status: 'ok' }); + }; + server.route({ method: 'GET', path: '/test', handler: handler }); + server.start(); + // All requests will get routed to '/test'*/ + ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + + /** server.handler(name, method) + Registers a new handler type to be used in routes where: + name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. + method - the function used to generate the route handler using the signature function(route, options) where: + route - the route public interface object. + options - the configuration object provided in the handler config. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + // Defines new handler for routes on this server + server.handler('test', function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }); + server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } + }); + server.start(); + The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + var handler = function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }; + // Change the default payload processing for this handler + handler.defaults = { + payload: { + output: 'stream', + parse: false + } + }; + server.handler('test', handler);*/ + handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; + + /** server.initialize([callback]) + Initializes the server (starts the caches, finalizes plugin registration) but does not start listening + on the connection ports, where: + - `callback` - the callback method when server initialization is completed or failed with the signature + `function(err)` where: + - `err` - any initialization error condition. + + If no `callback` is provided, a `Promise` object is returned. + + Note that if the method fails and the callback includes an error, the server is considered to be in + an undefined state and should be shut down. In most cases it would be impossible to fully recover as + the various plugins, caches, and other event listeners will get confused by repeated attempts to + start the server or make assumptions about the healthy state of the environment. It is recommended + to assert that no error has been returned after calling `initialize()` to abort the process when the + server fails to start properly. If you must try to resume after an error, call `server.stop()` + first to reset the server state. + */ + initialize(callback?: (error: any) => void): Promise; + + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var handler = function (request, reply) { + return reply('Success!'); + }; + server.route({ method: 'GET', path: '/', handler: handler }); + server.inject('/', function (res) { + console.log(res.result); + }); + */ + inject: IServerInject; + + /** server.log(tags, [data, [timestamp]]) + Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('log', function (event, tags) { + if (tags.error) { + console.log(event); + } + }); + server.log(['test', 'error'], 'Test event');*/ + log(tags: string | string[], data?: string | any, timestamp?: number): void; + + /**server.lookup(id) + When the server contains exactly one connection, looks up a route configuration where: + id - the route identifier as set in the route options. + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.lookup('root'); + When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ + lookup(id: string): IRoute; + + /** server.match(method, path, [host]) + When the server contains exactly one connection, looks up a route configuration where: + method - the HTTP method (e.g. 'GET', 'POST'). + path - the requested path (must begin with '/'). + host - optional hostname (to match against routes with vhost). + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.match('get', '/'); + When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ + match(method: string, path: string, host?: string): IRoute; + + /** server.method(name, method, [options]) + Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + Methods are registered via server.method(name, method, [options]) + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Simple arguments + var add = function (a, b, next) { + return next(null, a + b); + }; + server.method('sum', add, { cache: { expiresIn: 2000 } }); + server.methods.sum(4, 5, function (err, result) { + console.log(result); + }); + // Object argument + var addArray = function (array, next) { + var sum = 0; + array.forEach(function (item) { + sum += item; + }); + return next(null, sum); + }; + server.method('sumObj', addArray, { + cache: { expiresIn: 2000 }, + generateKey: function (array) { + return array.join(','); + } + }); + server.methods.sumObj([5, 6], function (err, result) { + console.log(result); + }); + // Synchronous method with cache + var addSync = function (a, b) { + return a + b; + }; + server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); + server.methods.sumSync(4, 5, function (err, result) { + console.log(result); + }); */ + method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ + name: string, + method: IServerMethod, + options?: IServerMethodOptions): void; + + /**server.method(methods) + Registers a server method function as described in server.method() using a configuration object where: + methods - an object or an array of objects where each one contains: + name - the method name. + method - the method function. + options - optional settings. + var add = function (a, b, next) { + next(null, a + b); + }; + server.method({ + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000 + } + } + });*/ + method(methods: { + name: string; method: IServerMethod; options?: IServerMethodOptions + } | Array<{ + name: string; method: IServerMethod; options?: IServerMethodOptions + }>): void; + + /**server.path(relativeTo) + Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + relativeTo - the path prefix added to any relative file path starting with '.'. + Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + exports.register = function (server, options, next) { + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); + };*/ + path(relativeTo: string): void; + + /** + * server.register(plugins, [options], callback) + * Registers a plugin where: + * plugins - an object or array of objects where each one is either: + * a plugin registration function. + * an object with the following: + * register - the plugin registration function. + * options - optional options passed to the registration function when called. + * options - optional registration options (different from the options passed to the registration function): + * select - a string or array of string labels used to pre-select connections for plugin registration. + * routes - modifiers applied to each route added by the plugin: + * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * callback - the callback function with signature function(err) where: + * err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + * + * If no callback is provided, a Promise object is returned. + */ + register( + plugins: any | any[], + options: { + select?: string | string[]; + routes: { + prefix: string; vhost?: string | string[] + }; + }, + callback: (err: any) => void): void; + register( + plugins: any | any[], + options: { + select?: string | string[]; + routes: { + prefix: string; vhost?: string | string[] + }; + }): Promise; + + register(plugins: any | any[], callback: (err: any) => void): void; + register(plugins: any | any[]): Promise; + + /**server.render(template, context, [options], callback) + Utilizes the server views manager to render a template where: + template - the template filename and path, relative to the views manager templates path (path or relativeTo). + context - optional object used by the template to render context-specific result. Defaults to no context ({}). + options - optional object used to override the views manager configuration. + callback - the callback function with signature function (err, rendered, config) where: + err - the rendering error if any. + rendered - the result view string. + config - the configuration used to render the template. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.views({ + engines: { html: require('handlebars') }, + path: __dirname + '/templates' + }); + var context = { + title: 'Views Example', + message: 'Hello, World' + }; + server.render('hello', context, function (err, rendered, config) { + console.log(rendered); + });*/ + render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; + + /** server.route(options) + Adds a connection route where: + options - a route configuration object or an array of configuration objects. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); + server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } + ]);*/ + route(options: IRouteConfiguration): void; + route(options: IRouteConfiguration[]): void; + + /**server.select(labels) + Selects a subset of the server's connections where: + labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, labels: ['a'] }); + server.connection({ port: 8080, labels: ['b'] }); + server.connection({ port: 8081, labels: ['c'] }); + server.connection({ port: 8082, labels: ['c','d'] }); + var a = server.select('a'); // The server with port 80 + var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 + var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ + select(labels: string | string[]): Server | Server[]; + + /** server.start([callback]) + Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: + callback - optional callback when server startup is completed or failed with the signature function(err) where: + err - any startup error condition. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.start(function (err) { + console.log('Server started at: ' + server.info.uri); + });*/ + start(callback?: (err: any) => void): Promise; + + /** server.state(name, [options]) + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions + State defaults can be modified via the server connections.routes.state configuration option. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Set cookie definition + server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' + }); + // Set state in route handler + var handler = function (request, reply) { + var session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + session.last = Date.now(); + return reply('Success').state('session', session); + }; + Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('request-internal', function (request, event, tags) { + if (tags.error && tags.state) { + console.error(event); + } + }); */ + state(name: string, options?: ICookieSettings): void; + + /** server.stop([options], [callback]) + Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + options - optional object with: + timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.stop({ timeout: 60 * 1000 }, function () { + console.log('Server stopped'); + });*/ + stop(options?: { timeout: number }, callback?: () => void): Promise; + + /**server.table([host]) + Returns a copy of the routing table where: + host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path. + Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.table(); + When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.connections[0].table(); + //[ + // { + // method: 'get', + // path: '/example', + // settings: { ... } + // } + //] + */ + table(host?: any): IConnectionTable; + + /**server.views(options) + Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ + views(options: IServerViewsConfiguration): void; +} diff --git a/types/hapi/v15/tsconfig.json b/types/hapi/v15/tsconfig.json new file mode 100644 index 0000000000..4a54b80605 --- /dev/null +++ b/types/hapi/v15/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "hapi": [ + "hapi/v15" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-tests.ts" + ] +} \ No newline at end of file diff --git a/types/hashids/hashids-tests.ts b/types/hashids/hashids-tests.ts index e1a6c094ec..e08465d01e 100644 --- a/types/hashids/hashids-tests.ts +++ b/types/hashids/hashids-tests.ts @@ -1,7 +1,7 @@ /* require hashids */ -import Hashids = require("hashids"); +import Hashids from 'hashids'; /* creating class object */ var hashids = new Hashids("this is my salt"); diff --git a/types/hashids/index.d.ts b/types/hashids/index.d.ts index d7c5ec56b7..8a3456a1f8 100644 --- a/types/hashids/index.d.ts +++ b/types/hashids/index.d.ts @@ -5,30 +5,24 @@ /// -declare namespace Hashids { - - export interface IHashids { - new(salt: string, minHashLength?: number, alphabet?: string): IHashids; - version: string; - minAlphabetLength: number; - sepDiv: number; - guardDiv: number; - errorAlphabetLength: string; - errorAlphabetSpace: string; - alphabet: string[]; - seps: string; - minHashLength: number; - salt: string; - decode(hash: string): number[]; - encode(arg: number): string; - encode(arg: number[]): string; - encode(...args: number[]): string; - encodeHex(str: string): string; - decodeHex(hash: string): string; - hash(input: number, alphabet: string): string; - unhash(input: string[], alphabet: string): number; - } +export default class Hashids { + private version: string; + private minAlphabetLength: number; + private sepDiv: number; + private guardDiv: number; + private errorAlphabetLength: string; + private errorAlphabetSpace: string; + private alphabet: string[]; + private seps: string; + private minHashLength: number; + private salt: string; + constructor(salt: string, minHashLength?: number, alphabet?: string); + public decode(hash: string): number[]; + public encode(arg: number): string; + public encode(arg: number[]): string; + public encode(...args: number[]): string; + public encodeHex(str: string): string; + public decodeHex(hash: string): string; + public hash(input: number, alphabet: string): string; + public unhash(input: string[], alphabet: string): number; } - -declare var hashids: Hashids.IHashids; -export = hashids; diff --git a/types/helmet/helmet-tests.ts b/types/helmet/helmet-tests.ts index 1968c8f848..38fa53828f 100644 --- a/types/helmet/helmet-tests.ts +++ b/types/helmet/helmet-tests.ts @@ -190,6 +190,13 @@ function noSniffTest() { app.use(helmet.noSniff()); } +/** + * @summary Test for {@see helmet#referrerPolicy} function. + */ +function referrerPolicyTest() { + app.use(helmet.referrerPolicy({ policy: 'same-origin' })) +} + /** * @summary Test for {@see helmet#xssFilter} function. */ diff --git a/types/helmet/index.d.ts b/types/helmet/index.d.ts index 1dc8882608..ee37b7d298 100644 --- a/types/helmet/index.d.ts +++ b/types/helmet/index.d.ts @@ -88,6 +88,10 @@ declare namespace helmet { force?: boolean; } + export interface IHelmetReferrerPolicyConfiguration { + policy?: string; + } + export interface IHelmetXssFilterConfiguration { setOnOldIE?: boolean; } @@ -163,6 +167,12 @@ declare namespace helmet { */ noSniff(): express.RequestHandler; + /** + * @summary Adds the "Referrer-Policy" header. + * @return {RequestHandler} The Request handler. + */ + referrerPolicy(options?: IHelmetReferrerPolicyConfiguration): express.RequestHandler; + /** * @summary Mitigate cross-site scripting attacks with the "X-XSS-Protection" header. * @param {IHelmetXssFilterConfiguration} options The options diff --git a/types/history/PathUtils.d.ts b/types/history/PathUtils.d.ts index 7ea7ed75a4..4cc947fcf3 100644 --- a/types/history/PathUtils.d.ts +++ b/types/history/PathUtils.d.ts @@ -1,7 +1,7 @@ -import { Path, Location, LocationDescriptor } from './index'; +import { Path, Location, LocationDescriptorObject } from './index'; export function addLeadingSlash(path: Path): Path; export function stripLeadingSlash(path: Path): Path; export function stripPrefix(path: Path, prefix: string): Path; export function parsePath(path: Path): Location; -export function createPath(location: LocationDescriptor): Path; +export function createPath(location: LocationDescriptorObject): Path; diff --git a/types/history/index.d.ts b/types/history/index.d.ts index a45b930efe..eda8c1bb10 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -20,7 +20,7 @@ export interface History { goForward(): void; block(prompt?: boolean): UnregisterCallback; listen(listener: LocationListener): UnregisterCallback; - createHref(location: Path | LocationDescriptorObject): Href; + createHref(location: LocationDescriptorObject): Href; } export interface Location { diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index e51f2f495c..2d3f6d3b04 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -55,7 +55,20 @@ i18n.init({ interpolation: {}, detection: null, backend: null, - cache: null + cache: null, + wait: false +}); + +i18n.init({ + fallbackLng: ['en', 'ru'], +}); + +i18n.init({ + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, }); i18n.t('helloWorld', { @@ -69,6 +82,22 @@ i18n.t('helloWorldInterpolated', { name: "world" }); +i18n.t('helloSingleFallbackLng', { + fallbackLng: 'en' +}); + +i18n.t('helloMultiFallbackLng', { + fallbackLng: ['en', 'ru'] +}); + +i18n.t('helloObjectFallbackLng', { + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, +}); + i18n.exists("helloWorld"); const options:i18n.Options = i18n.options; diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index ee06d8d18c..1cacdeb7c3 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for i18next v2.3.4 +// Type definitions for i18next v2.3.5 // Project: http://i18next.com -// Definitions by: Michael Ledin +// Definitions by: Michael Ledin , Budi Irawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Sources: https://github.com/i18next/i18next/ @@ -19,6 +19,12 @@ declare namespace i18n { [key: string]: any; } + interface FallbackLngObjList { + [language: string]: string[] + } + + type FallbackLng = string | string[] | FallbackLngObjList; + interface InterpolationOptions { escapeValue?: boolean; prefix?: string; @@ -41,7 +47,7 @@ declare namespace i18n { replace?: any; lng?: string; lngs?: string[]; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; keySeparator?: string; nsSeparator?: string; @@ -57,7 +63,7 @@ declare namespace i18n { debug?: boolean; resources?: ResourceStore; lng?: string; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; defaultNS?: string; fallbackNS?: string | string[]; @@ -87,12 +93,17 @@ declare namespace i18n { cache?: any; } + // init options for react-i18next + interface ReactOptions { + wait?: boolean; + } + type TranslationFunction = (key: string, options?: TranslationOptions) => string; interface I18n { //constructor(options?: Options, callback?: (err: any, t: TranslationFunction) => void); - init(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; + init(options?: Options&ReactOptions, callback?: (err: any, t: TranslationFunction) => void): I18n; loadResources(callback?: (err: any) => void): void; diff --git a/types/images/images-tests.ts b/types/images/images-tests.ts new file mode 100644 index 0000000000..fc5cab619b --- /dev/null +++ b/types/images/images-tests.ts @@ -0,0 +1,35 @@ +import * as images from "images"; + +// from https://github.com/zhangyuanwei/node-images/blob/master/demo/uploadServer.js +let tmp_path = "tmp_path"; +let out_path = "out_path"; +let photo = images(tmp_path); + +photo.size(800) + .draw(images('./logo.png'), 800 - 421, photo.height() - 117) + .save(out_path, { quality: 80 }); + +// from https://github.com/zhangyuanwei/node-images/blob/master/test/index.js +images("input.png") + .resize(200) + .save("output_new.png"); + +images("input.png") + .size(200) + .save("output_old.png"); + +images("input.jpg") + .resize(200) + .save("output_new.jpg"); + +images("input.jpg") + .size(200) + .save("output_old.jpg"); + +images("input.gif") + .resize(200) + .save("output_new_gif.jpg"); + +images("input.gif") + .size(200) + .save("output_old_gif.jpg"); diff --git a/types/images/index.d.ts b/types/images/index.d.ts new file mode 100644 index 0000000000..38484bb256 --- /dev/null +++ b/types/images/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for images 2.2 +// Project: https://github.com/zhangyuanwei/node-images +// Definitions by: Ding Weizhe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace images { + interface ImagesConfig { + [key: string]: any; + } + type SupportType = "png" | "jpg" | "gif" | "bmp" | "raw" | "webp"; + class ImagesStatic { + fill(red: number, green: number, blue: number, alpha?: number): ImagesStatic; + draw(image: ImagesStatic, x: number, y: number): ImagesStatic; + loadFromBuffer(buffer: Buffer): ImagesStatic; + encode(type: string, config?: ImagesConfig): void; + save(file: string, type?: SupportType, config?: ImagesConfig): void; + save(file: string, config?: ImagesConfig): void; + size(): { width: number, height: number }; + size(width: number, height?: number): ImagesStatic; + resize(width: number, height?: number, filter?: string): ImagesStatic; + resize(width: number, height: number, filter?: string): ImagesStatic; + width(): number; + width(width: number): ImagesStatic; + height(): number; + height(height: number): ImagesStatic; + setLimit(width: number, height: number): void; + setGCThreshold(value: number): void; + getUsedMemory(): void; + gc(): void; + } +} + +/* tslint:disable:unified-signatures */ +declare function images(file: string): images.ImagesStatic; +declare function images(width: number, height: number): images.ImagesStatic; +declare function images(buffer: Buffer, start?: number, end?: number): images.ImagesStatic; +declare function images(image: images.ImagesStatic): images.ImagesStatic; +declare function images(image: images.ImagesStatic, x: number, y: number, width: number, height: number): images.ImagesStatic; +/* tslint:enable:unified-signatures */ + +export = images; diff --git a/types/images/tsconfig.json b/types/images/tsconfig.json new file mode 100644 index 0000000000..7a261dbc3f --- /dev/null +++ b/types/images/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "images-tests.ts" + ] +} diff --git a/types/images/tslint.json b/types/images/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/images/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index cb9b8e8edb..a54841eac7 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -5,10 +5,8 @@ import * as hapi from 'hapi'; -declare module 'hapi' { - interface IFileHandler { - /** path - a path string or function as described above (required). */ - path: string | IRequestHandler; +declare namespace inert { + export interface ReplyFileHandlerOptions { /** confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. */ confine?: boolean; /** filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path */ @@ -37,13 +35,18 @@ declare module 'hapi' { end?: number; } - interface IDirectoryHandler { + export interface FileHandlerRouteObject extends ReplyFileHandlerOptions { + /** path - a path string or function as described above (required). */ + path: string | hapi.RequestHandler; + } + + export interface DirectoryHandlerRouteObject { /** path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: * * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. * * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). * * a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. */ - path: string | string[] | IRequestHandler; + path: string | string[] | hapi.RequestHandler; /** index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. */ index?: boolean | string | string[]; /** listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. */ @@ -65,23 +68,48 @@ declare module 'hapi' { defaultExtension?: string; } - interface IRouteConfiguration { + /** + * inert accepts the following registration options + * @see {@link https://github.com/hapijs/inert#registration-options} + */ + interface OptionalRegistrationOptions { + /** + * sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000. + */ + etagsCacheMaxSize?: number; + } +} + +declare module 'hapi' { + interface RouteHandlerPlugins { /** * The file handler * * Generates a static file endpoint for serving a single file. file can be set to: * * a relative or absolute file path string (relative paths are resolved based on the route files configuration). * * a function with the signature function(request) which returns the relative or absolute file path. - * * an object with one or more of the following options: + * * an object with one or more of the following options @see IFileHandler * @see {@link https://github.com/hapijs/inert#the-file-handler} */ - file?: string | IRequestHandler | IFileHandler; + file?: string | RequestHandler | inert.FileHandlerRouteObject; /** * The directory handler * * Generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: * @see {@link https://github.com/hapijs/inert#the-directory-handler} */ - directory?: IDirectoryHandler; + directory?: inert.DirectoryHandlerRouteObject; + } + + interface Base_Reply { + /** + * Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. + * @see {@link https://github.com/hapijs/inert#replyfilepath-options} + */ + file: (path: string, options?: inert.ReplyFileHandlerOptions) => Response; } } + +declare var inert: hapi.PluginFunction; + +export = inert; diff --git a/types/inert/inert-tests.ts b/types/inert/inert-tests.ts index 38830694cd..82cd1f1295 100644 --- a/types/inert/inert-tests.ts +++ b/types/inert/inert-tests.ts @@ -1,36 +1,132 @@ -import * as HapiES6 from 'hapi'; -import * as InertES6 from 'inert'; +// Copied from: https://github.com/hapijs/inert#examples -const server = new HapiES6.Server({}); -server.register(InertES6, () => {}); +/// + +import Path = require('path'); +import Hapi = require('hapi'); +import Inert = require('inert'); + +const server = new Hapi.Server({ + connections: { + routes: { + files: { + relativeTo: Path.join(__dirname, 'public') + } + } + } +}); +server.connection({ port: 3000 }); + +server.register(Inert, () => {}); + +// added in addition to code from docs +const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; +server.register({ + register: Inert, + options, +}, (err) => {}); + +// added in addition to code from docs +server.register({ + register: Inert, + once: true, +}, (err) => {}); + +server.route({ + method: 'GET', + path: '/{param*}', + handler: { + directory: { + path: '.', + redirectToSlash: true, + index: true + } + } +}); + +server.start((err) => { + + if (err) { + throw err; + } + + console.log('Server running at:', server.info!.uri); +}); + +// https://github.com/hapijs/inert#serving-a-single-file + +server.route({ + method: 'GET', + path: '/{path*}', + handler: { + file: 'page.html' + } +}); + +// https://github.com/hapijs/inert#customized-file-response + +server.route({ + method: 'GET', + path: '/file', + handler: function (request, reply) { + + let path = 'plain.txt'; + if (request.headers['x-magic'] === 'sekret') { + path = 'awesome.png'; + } + + return reply.file(path).vary('x-magic'); + } +}); + +const handler: Hapi.ServerExtRequestHandler = function (request, reply) { + + const response = request.response!; + if (response.isBoom && + response.output!.statusCode === 404) { + + return reply.file('404.html').code(404); + } + + return reply.continue(); +} + +server.ext('onPostHandler', handler); + +// additional code added in addition to doc example code + +var file: Inert.FileHandlerRouteObject = { + path: '', + confine: true, +}; +var directory: Inert.DirectoryHandlerRouteObject = { + path: '', + listing: true +}; + +file = { + path: '', + confine: true, +}; server.route({ path: '', method: 'GET', - file: { - path: '', - confine: true, + handler: { + file, + directory: { + path: function(){ + if(Math.random() > 0.5) { + return ''; + } + else if(Math.random() > 0) { + return ['']; + } + return new Error(''); + }, + BAD_listing: true, // TODO change typings to make this error + }, }, - directory: { - path: '', - listing: true - } + config: { files: { relativeTo: __dirname } } }) -var fileHandler: HapiES6.IFileHandler = { - path: '', - confine: true, -} - -var directoryHandler: HapiES6.IDirectoryHandler = { - path: function(){ - if(Math.random() > 0.5) { - return ''; - } - else if(Math.random() > 0) { - return ['']; - } - return new Error(''); - }, - listing: true, -} diff --git a/types/inquirer/index.d.ts b/types/inquirer/index.d.ts index 1909781f88..dd2f4ad3c7 100644 --- a/types/inquirer/index.d.ts +++ b/types/inquirer/index.d.ts @@ -94,7 +94,7 @@ declare namespace inquirer { * Receive the user input and should return true if the value is valid, and an error message (String) * otherwise. If false is returned, a default error message is provided. */ - validate?(input: string): boolean | string; + validate?(input: string, answers?: Answers): boolean | string; /** * Receive the user input and return the filtered value to be used inside the program. * The value returned will be added to the Answers hash. @@ -106,6 +106,10 @@ declare namespace inquirer { */ when?: boolean | ((answers: Answers) => boolean); paginated?: boolean; + /** + * Change the number of lines that will be rendered when using list, rawList, expand or checkbox. + */ + pageSize?: number; } /** diff --git a/types/isomorphic-fetch/index.d.ts b/types/isomorphic-fetch/index.d.ts index 00b40fe911..7fbc0d8ed2 100644 --- a/types/isomorphic-fetch/index.d.ts +++ b/types/isomorphic-fetch/index.d.ts @@ -2,116 +2,8 @@ // Project: https://github.com/matthew-andrews/isomorphic-fetch // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -interface ForEachCallback { - (keyId: any, status: string): void; -} - -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - forEach(callback: ForEachCallback): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; -} - -declare var Headers: { - prototype: Headers; - new(init?: any): Headers; -} - -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -interface Body { - readonly bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - json(): Promise; - text(): Promise; -} - -interface RequestInit { - method?: string; - headers?: any; - body?: any; - referrer?: string; - referrerPolicy?: string; - mode?: string; - credentials?: string; - cache?: string; - redirect?: string; - integrity?: string; - keepalive?: boolean; - window?: any; -} - -interface Request extends Object, Body { - readonly cache: string; - readonly credentials: string; - readonly destination: string; - readonly headers: Headers; - readonly integrity: string; - readonly keepalive: boolean; - readonly method: string; - readonly mode: string; - readonly redirect: string; - readonly referrer: string; - readonly referrerPolicy: string; - readonly type: string; - readonly url: string; - clone(): Request; -} - -declare var Request: { - prototype: Request; - new(input: Request | string, init?: RequestInit): Request; -} - -interface ReadableStream { - readonly locked: boolean; - cancel(): Promise; -} - -interface ResponseInit { - status?: number; - statusText?: string; - headers?: any; -} - -interface Response extends Object, Body { - readonly body: ReadableStream | null; - readonly headers: Headers; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly type: string; - readonly url: string; - clone(): Response; -} - -declare var Response: { - prototype: Response; - new(body?: any, init?: ResponseInit): Response; -} - -interface GlobalFetch { - fetch(input: Request | string, init?: RequestInit): Promise; -} - -interface Window extends GlobalFetch { -} - -declare function fetch(input: Request | string, init?: RequestInit): Promise; - -declare module "isomorphic-fetch" { - namespace _fetch { } - const _fetch: typeof fetch; - export = _fetch; -} +declare namespace _fetch { } +declare const _fetch: typeof fetch; +export = _fetch; diff --git a/types/isomorphic-fetch/isomorphic-fetch-tests.ts b/types/isomorphic-fetch/isomorphic-fetch-tests.ts index ac1a008350..6c5ad99a68 100644 --- a/types/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/types/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -1,4 +1,3 @@ -/// import fetchImportedViaCommonJS = require('isomorphic-fetch'); import * as fetchImportedViaES6Module from 'isomorphic-fetch'; @@ -35,13 +34,12 @@ function test_isomorphicFetchTestCases_es6() { }); } - function test_whatwgTestCases_ambient() { - var headers = new Headers(); + const headers = new Headers(); headers.append("Content-Type", "application/json"); - var requestOptions: RequestInit = { + let requestOptions: RequestInit = { method: "POST", - headers: headers, + headers, mode: 'same-origin', credentials: 'omit', cache: 'default' @@ -49,7 +47,7 @@ function test_whatwgTestCases_ambient() { expectSuccess(fetch('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' @@ -58,23 +56,23 @@ function test_whatwgTestCases_ambient() { expectSuccess(fetch('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' } }; - var request: Request = new Request('http://localhost:3000/poster', requestOptions); + const request: Request = new Request('http://localhost:3000/poster', requestOptions); expectSuccess(fetch(request), 'Post response:'); } function test_whatwgTestCases_commonjs() { - var headers = new Headers(); + const headers = new Headers(); headers.append("Content-Type", "application/json"); - var requestOptions: RequestInit = { + let requestOptions: RequestInit = { method: "POST", - headers: headers, + headers, mode: 'same-origin', credentials: 'omit', cache: 'default' @@ -82,7 +80,7 @@ function test_whatwgTestCases_commonjs() { expectSuccess(fetchImportedViaCommonJS('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' @@ -91,23 +89,23 @@ function test_whatwgTestCases_commonjs() { expectSuccess(fetchImportedViaCommonJS('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' } }; - var request: Request = new Request('http://localhost:3000/poster', requestOptions); + const request: Request = new Request('http://localhost:3000/poster', requestOptions); expectSuccess(fetchImportedViaCommonJS(request), 'Post response:'); } function test_whatwgTestCases_es6() { - var headers = new Headers(); + const headers = new Headers(); headers.append("Content-Type", "application/json"); - var requestOptions: RequestInit = { + let requestOptions: RequestInit = { method: "POST", - headers: headers, + headers, mode: 'same-origin', credentials: 'omit', cache: 'default' @@ -115,7 +113,7 @@ function test_whatwgTestCases_es6() { expectSuccess(fetchImportedViaES6Module('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' @@ -124,13 +122,13 @@ function test_whatwgTestCases_es6() { expectSuccess(fetchImportedViaES6Module('http://localhost:3000/poster', requestOptions), 'Post response:'); - var requestOptions: RequestInit = { + requestOptions = { method: "POST", headers: { 'Content-Type': 'application/json' } }; - var request: Request = new Request('http://localhost:3000/poster', requestOptions); + const request: Request = new Request('http://localhost:3000/poster', requestOptions); expectSuccess(fetchImportedViaES6Module(request), 'Post response:'); } diff --git a/types/isomorphic-fetch/tslint.json b/types/isomorphic-fetch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/isomorphic-fetch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine-ajax/index.d.ts b/types/jasmine-ajax/index.d.ts index 4762ba085a..dcc6720f04 100644 --- a/types/jasmine-ajax/index.d.ts +++ b/types/jasmine-ajax/index.d.ts @@ -27,13 +27,13 @@ interface JasmineAjaxRequest extends XMLHttpRequest { } interface JasmineAjaxRequestTracker { - track(request: JasmineAjaxRequest): void; - first(): JasmineAjaxRequest; - count(): number; - reset(): void; - mostRecent(): JasmineAjaxRequest; - at(index: number): JasmineAjaxRequest; - filter(urlToMatch: RegExp): JasmineAjaxRequest[]; + track(request: JasmineAjaxRequest): void; + first(): JasmineAjaxRequest; + count(): number; + reset(): void; + mostRecent(): JasmineAjaxRequest; + at(index: number): JasmineAjaxRequest; + filter(urlToMatch: RegExp): JasmineAjaxRequest[]; filter(urlToMatch: Function): JasmineAjaxRequest[]; filter(urlToMatch: string): JasmineAjaxRequest[]; } @@ -48,14 +48,14 @@ interface JasmineAjaxRequestStubReturnOptions { interface JasmineAjaxRequestStub { data?: string; - method?: string; - andReturn(options: JasmineAjaxRequestStubReturnOptions): void; - matches(fullUrl: string, data: string, method: string): boolean; + method?: string; + andReturn(options: JasmineAjaxRequestStubReturnOptions): void; + matches(fullUrl: string, data: string, method: string): boolean; } interface JasmineAjaxStubTracker { - addStub(stub: JasmineAjaxRequestStub): void; - reset(): void; + addStub(stub: JasmineAjaxRequestStub): void; + reset(): void; findStub(url: string, data?: string, method?: string): JasmineAjaxRequestStub; } diff --git a/types/jasmine-ajax/jasmine-ajax-tests.ts b/types/jasmine-ajax/jasmine-ajax-tests.ts index b2c963c6c1..fabd525012 100644 --- a/types/jasmine-ajax/jasmine-ajax-tests.ts +++ b/types/jasmine-ajax/jasmine-ajax-tests.ts @@ -1779,7 +1779,7 @@ describe("mockAjax", () => { mockAjax.install(); - mockAjax.requests.track( { url: '/testurl' }); + // mockAjax.requests.track( { url: '/testurl' }); mockAjax.stubRequest('/bobcat'); expect(mockAjax.requests.count()).toEqual(1); diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 595a42ea2b..36011e67a7 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -291,6 +291,7 @@ declare function pending(reason?: string): void; /** Fails a test when called within one. */ declare function fail(error?: any): void; declare namespace jasmine { + var DEFAULT_TIMEOUT_INTERVAL: number; var clock: () => Clock; function any(aclass: any): Any; function anything(): Any; diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index c11bcb9daf..dbf134e541 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -167,6 +167,14 @@ export interface Reference extends Schema { } export interface AnySchema> { + /** + * Validates a value using the schema and options. + */ + validate(value: T): ValidationResult; + validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, callback: (err: ValidationError, value: T) => R): R; + validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + /** * Whitelists a value */ @@ -567,7 +575,8 @@ export interface ArraySchema extends AnySchema { * Be aware that a deep equality is performed on elements of the array having a type of object, * a performance penalty is to be expected for this kind of operation. */ - unique(): ArraySchema; + unique(comparator?: (a: any, b: any) => boolean): ArraySchema; + unique(comparator?: string): ArraySchema; } export interface ObjectSchema extends AnySchema { diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index f35a124183..3cd2e28b73 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -50,87 +50,87 @@ var ref: Joi.Reference = null; var validOpts: Joi.ValidationOptions = null; -validOpts = {abortEarly: bool}; -validOpts = {convert: bool}; -validOpts = {allowUnknown: bool}; -validOpts = {skipFunctions: bool}; -validOpts = {stripUnknown: bool}; -validOpts = {stripUnknown: {arrays: bool}}; -validOpts = {stripUnknown: {objects: bool}}; -validOpts = {stripUnknown: {arrays: bool, objects: bool}}; -validOpts = {language: bool}; -validOpts = {presence: str}; -validOpts = {context: obj}; -validOpts = {noDefaults: bool}; +validOpts = { abortEarly: bool }; +validOpts = { convert: bool }; +validOpts = { allowUnknown: bool }; +validOpts = { skipFunctions: bool }; +validOpts = { stripUnknown: bool }; +validOpts = { stripUnknown: { arrays: bool } }; +validOpts = { stripUnknown: { objects: bool } }; +validOpts = { stripUnknown: { arrays: bool, objects: bool } }; +validOpts = { language: bool }; +validOpts = { presence: str }; +validOpts = { context: obj }; +validOpts = { noDefaults: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var renOpts: Joi.RenameOptions = null; -renOpts = {alias: bool}; -renOpts = {multiple: bool}; -renOpts = {override: bool}; -renOpts = {ignoreUndefined: bool}; +renOpts = { alias: bool }; +renOpts = { multiple: bool }; +renOpts = { override: bool }; +renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var emailOpts: Joi.EmailOptions = null; -emailOpts = {errorLevel: num}; -emailOpts = {errorLevel: bool}; -emailOpts = {tldWhitelist: strArr}; -emailOpts = {tldWhitelist: obj}; -emailOpts = {minDomainAtoms: num}; +emailOpts = { errorLevel: num }; +emailOpts = { errorLevel: bool }; +emailOpts = { tldWhitelist: strArr }; +emailOpts = { tldWhitelist: obj }; +emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var ipOpts: Joi.IpOptions = null; -ipOpts = {version: str}; -ipOpts = {version: strArr}; -ipOpts = {cidr: str}; +ipOpts = { version: str }; +ipOpts = { version: strArr }; +ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var uriOpts: Joi.UriOptions = null; -uriOpts = {scheme: str}; -uriOpts = {scheme: exp}; -uriOpts = {scheme: strArr}; -uriOpts = {scheme: expArr}; +uriOpts = { scheme: str }; +uriOpts = { scheme: exp }; +uriOpts = { scheme: strArr }; +uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var whenOpts: Joi.WhenOptions = null; -whenOpts = {is: x}; -whenOpts = {is: schema, then: schema}; -whenOpts = {is: schema, otherwise: schema}; +whenOpts = { is: x }; +whenOpts = { is: schema, then: schema }; +whenOpts = { is: schema, otherwise: schema }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var refOpts: Joi.ReferenceOptions = null; -refOpts = {separator: str}; -refOpts = {contextPrefix: str}; +refOpts = { separator: str }; +refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var validErr: Joi.ValidationError = null; var validErrItem: Joi.ValidationErrorItem; -validErrItem= { - message: str, - type: str, - path: str +validErrItem = { + message: str, + type: str, + path: str }; validErrItem = { - message: str, - type: str, - path: str, - options: validOpts, - context: obj + message: str, + type: str, + path: str, + options: validOpts, + context: obj }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -162,23 +162,23 @@ anySchema = objSchema; var schemaMap: Joi.SchemaMap = null; schemaMap = { - a: numSchema, - b: strSchema + a: numSchema, + b: strSchema }; schemaMap = { - a: numSchema, - b: { - b1: strSchema, - b2: anySchema - } + a: numSchema, + b: { + b1: strSchema, + b2: anySchema + } }; schemaMap = { - a: numSchema, - b: [ - { b1: strSchema }, - { b2: anySchema } - ], - c: arrSchema + a: numSchema, + b: [ + { b1: strSchema }, + { b2: anySchema } + ], + c: arrSchema }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -186,63 +186,63 @@ schemaMap = { anySchema = Joi.any(); namespace common { - anySchema = anySchema.allow(x); - anySchema = anySchema.allow(x, x); - anySchema = anySchema.allow([x, x, x]); - anySchema = anySchema.valid(x); - anySchema = anySchema.valid(x, x); - anySchema = anySchema.valid([x, x, x]); - anySchema = anySchema.only(x); - anySchema = anySchema.only(x, x); - anySchema = anySchema.only([x, x, x]); - anySchema = anySchema.equal(x); - anySchema = anySchema.equal(x, x); - anySchema = anySchema.equal([x, x, x]); - anySchema = anySchema.invalid(x); - anySchema = anySchema.invalid(x, x); - anySchema = anySchema.invalid([x, x, x]); - anySchema = anySchema.disallow(x); - anySchema = anySchema.disallow(x, x); - anySchema = anySchema.disallow([x, x, x]); - anySchema = anySchema.not(x); - anySchema = anySchema.not(x, x); - anySchema = anySchema.not([x, x, x]); + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); - anySchema = anySchema.default(); - anySchema = anySchema.default(x); - anySchema = anySchema.default(x, str); + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); - anySchema = anySchema.required(); - anySchema = anySchema.optional(); - anySchema = anySchema.forbidden(); - anySchema = anySchema.strip(); + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); - anySchema = anySchema.description(str); - anySchema = anySchema.notes(str); - anySchema = anySchema.notes(strArr); - anySchema = anySchema.tags(str); - anySchema = anySchema.tags(strArr); + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); - anySchema = anySchema.meta(obj); - anySchema = anySchema.example(obj); - anySchema = anySchema.unit(str); + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); - anySchema = anySchema.options(validOpts); - anySchema = anySchema.strict(); - anySchema = anySchema.strict(bool); - anySchema = anySchema.concat(x); + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); - altSchema = anySchema.when(str, whenOpts); - altSchema = anySchema.when(ref, whenOpts); + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); - anySchema = anySchema.label(str); - anySchema = anySchema.raw(); - anySchema = anySchema.raw(bool); - anySchema = anySchema.empty(); - anySchema = anySchema.empty(str); - anySchema = anySchema.empty(anySchema); + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); - anySchema = anySchema.error(err); + anySchema = anySchema.error(err); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -261,6 +261,8 @@ arrSchema = arrSchema.min(num); arrSchema = arrSchema.max(num); arrSchema = arrSchema.length(num); arrSchema = arrSchema.unique(); +arrSchema = arrSchema.unique((a, b) => a.test === b.test); +arrSchema = arrSchema.unique('customer.id'); arrSchema = arrSchema.items(numSchema); @@ -273,51 +275,51 @@ arrSchema = arrSchema.items([schemaMap, schemaMap]); // - - - - - - - - namespace common_copy_paste { - // use search & replace from any - arrSchema = arrSchema.allow(x); - arrSchema = arrSchema.allow(x, x); - arrSchema = arrSchema.allow([x, x, x]); - arrSchema = arrSchema.valid(x); - arrSchema = arrSchema.valid(x, x); - arrSchema = arrSchema.valid([x, x, x]); - arrSchema = arrSchema.only(x); - arrSchema = arrSchema.only(x, x); - arrSchema = arrSchema.only([x, x, x]); - arrSchema = arrSchema.equal(x); - arrSchema = arrSchema.equal(x, x); - arrSchema = arrSchema.equal([x, x, x]); - arrSchema = arrSchema.invalid(x); - arrSchema = arrSchema.invalid(x, x); - arrSchema = arrSchema.invalid([x, x, x]); - arrSchema = arrSchema.disallow(x); - arrSchema = arrSchema.disallow(x, x); - arrSchema = arrSchema.disallow([x, x, x]); - arrSchema = arrSchema.not(x); - arrSchema = arrSchema.not(x, x); - arrSchema = arrSchema.not([x, x, x]); + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); - arrSchema = arrSchema.default(x); + arrSchema = arrSchema.default(x); - arrSchema = arrSchema.required(); - arrSchema = arrSchema.optional(); - arrSchema = arrSchema.forbidden(); + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); - arrSchema = arrSchema.description(str); - arrSchema = arrSchema.notes(str); - arrSchema = arrSchema.notes(strArr); - arrSchema = arrSchema.tags(str); - arrSchema = arrSchema.tags(strArr); + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); - arrSchema = arrSchema.meta(obj); - arrSchema = arrSchema.example(obj); - arrSchema = arrSchema.unit(str); + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); - arrSchema = arrSchema.options(validOpts); - arrSchema = arrSchema.strict(); - arrSchema = arrSchema.concat(x); + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); - altSchema = arrSchema.when(str, whenOpts); - altSchema = arrSchema.when(ref, whenOpts); + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -326,68 +328,68 @@ boolSchema = Joi.bool(); boolSchema = Joi.boolean(); namespace common_copy_paste { - boolSchema = boolSchema.allow(x); - boolSchema = boolSchema.allow(x, x); - boolSchema = boolSchema.allow([x, x, x]); - boolSchema = boolSchema.valid(x); - boolSchema = boolSchema.valid(x, x); - boolSchema = boolSchema.valid([x, x, x]); - boolSchema = boolSchema.only(x); - boolSchema = boolSchema.only(x, x); - boolSchema = boolSchema.only([x, x, x]); - boolSchema = boolSchema.equal(x); - boolSchema = boolSchema.equal(x, x); - boolSchema = boolSchema.equal([x, x, x]); - boolSchema = boolSchema.invalid(x); - boolSchema = boolSchema.invalid(x, x); - boolSchema = boolSchema.invalid([x, x, x]); - boolSchema = boolSchema.disallow(x); - boolSchema = boolSchema.disallow(x, x); - boolSchema = boolSchema.disallow([x, x, x]); - boolSchema = boolSchema.not(x); - boolSchema = boolSchema.not(x, x); - boolSchema = boolSchema.not([x, x, x]); + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); - boolSchema = boolSchema.default(x); + boolSchema = boolSchema.default(x); - boolSchema = boolSchema.required(); - boolSchema = boolSchema.optional(); - boolSchema = boolSchema.forbidden(); + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); - boolSchema = boolSchema.description(str); - boolSchema = boolSchema.notes(str); - boolSchema = boolSchema.notes(strArr); - boolSchema = boolSchema.tags(str); - boolSchema = boolSchema.tags(strArr); + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); - boolSchema = boolSchema.meta(obj); - boolSchema = boolSchema.example(obj); - boolSchema = boolSchema.unit(str); + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); - boolSchema = boolSchema.options(validOpts); - boolSchema = boolSchema.strict(); - boolSchema = boolSchema.concat(x); + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); - boolSchema = boolSchema.truthy(str); - boolSchema = boolSchema.truthy(num); - boolSchema = boolSchema.truthy(strArr); - boolSchema = boolSchema.truthy(numArr); - boolSchema = boolSchema.truthy(str, str); - boolSchema = boolSchema.truthy(strArr, str); - boolSchema = boolSchema.truthy(str, strArr); - boolSchema = boolSchema.truthy(strArr, strArr); - boolSchema = boolSchema.falsy(str); - boolSchema = boolSchema.falsy(num); - boolSchema = boolSchema.falsy(strArr); - boolSchema = boolSchema.falsy(numArr); - boolSchema = boolSchema.falsy(str, str); - boolSchema = boolSchema.falsy(strArr, str); - boolSchema = boolSchema.falsy(str, strArr); - boolSchema = boolSchema.falsy(strArr, strArr); - boolSchema = boolSchema.insensitive(bool); + boolSchema = boolSchema.truthy(str); + boolSchema = boolSchema.truthy(num); + boolSchema = boolSchema.truthy(strArr); + boolSchema = boolSchema.truthy(numArr); + boolSchema = boolSchema.truthy(str, str); + boolSchema = boolSchema.truthy(strArr, str); + boolSchema = boolSchema.truthy(str, strArr); + boolSchema = boolSchema.truthy(strArr, strArr); + boolSchema = boolSchema.falsy(str); + boolSchema = boolSchema.falsy(num); + boolSchema = boolSchema.falsy(strArr); + boolSchema = boolSchema.falsy(numArr); + boolSchema = boolSchema.falsy(str, str); + boolSchema = boolSchema.falsy(strArr, str); + boolSchema = boolSchema.falsy(str, strArr); + boolSchema = boolSchema.falsy(strArr, strArr); + boolSchema = boolSchema.insensitive(bool); - altSchema = boolSchema.when(str, whenOpts); - altSchema = boolSchema.when(ref, whenOpts); + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -400,50 +402,50 @@ binSchema = binSchema.max(num); binSchema = binSchema.length(num); namespace common { - binSchema = binSchema.allow(x); - binSchema = binSchema.allow(x, x); - binSchema = binSchema.allow([x, x, x]); - binSchema = binSchema.valid(x); - binSchema = binSchema.valid(x, x); - binSchema = binSchema.valid([x, x, x]); - binSchema = binSchema.only(x); - binSchema = binSchema.only(x, x); - binSchema = binSchema.only([x, x, x]); - binSchema = binSchema.equal(x); - binSchema = binSchema.equal(x, x); - binSchema = binSchema.equal([x, x, x]); - binSchema = binSchema.invalid(x); - binSchema = binSchema.invalid(x, x); - binSchema = binSchema.invalid([x, x, x]); - binSchema = binSchema.disallow(x); - binSchema = binSchema.disallow(x, x); - binSchema = binSchema.disallow([x, x, x]); - binSchema = binSchema.not(x); - binSchema = binSchema.not(x, x); - binSchema = binSchema.not([x, x, x]); + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); - binSchema = binSchema.default(x); + binSchema = binSchema.default(x); - binSchema = binSchema.required(); - binSchema = binSchema.optional(); - binSchema = binSchema.forbidden(); + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); - binSchema = binSchema.description(str); - binSchema = binSchema.notes(str); - binSchema = binSchema.notes(strArr); - binSchema = binSchema.tags(str); - binSchema = binSchema.tags(strArr); + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); - binSchema = binSchema.meta(obj); - binSchema = binSchema.example(obj); - binSchema = binSchema.unit(str); + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); - binSchema = binSchema.options(validOpts); - binSchema = binSchema.strict(); - binSchema = binSchema.concat(x); + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); - altSchema = binSchema.when(str, whenOpts); - altSchema = binSchema.when(ref, whenOpts); + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -472,50 +474,50 @@ dateSchema = dateSchema.timestamp('javascript'); dateSchema = dateSchema.timestamp('unix'); namespace common { - dateSchema = dateSchema.allow(x); - dateSchema = dateSchema.allow(x, x); - dateSchema = dateSchema.allow([x, x, x]); - dateSchema = dateSchema.valid(x); - dateSchema = dateSchema.valid(x, x); - dateSchema = dateSchema.valid([x, x, x]); - dateSchema = dateSchema.only(x); - dateSchema = dateSchema.only(x, x); - dateSchema = dateSchema.only([x, x, x]); - dateSchema = dateSchema.equal(x); - dateSchema = dateSchema.equal(x, x); - dateSchema = dateSchema.equal([x, x, x]); - dateSchema = dateSchema.invalid(x); - dateSchema = dateSchema.invalid(x, x); - dateSchema = dateSchema.invalid([x, x, x]); - dateSchema = dateSchema.disallow(x); - dateSchema = dateSchema.disallow(x, x); - dateSchema = dateSchema.disallow([x, x, x]); - dateSchema = dateSchema.not(x); - dateSchema = dateSchema.not(x, x); - dateSchema = dateSchema.not([x, x, x]); + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); - dateSchema = dateSchema.default(x); + dateSchema = dateSchema.default(x); - dateSchema = dateSchema.required(); - dateSchema = dateSchema.optional(); - dateSchema = dateSchema.forbidden(); + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); - dateSchema = dateSchema.description(str); - dateSchema = dateSchema.notes(str); - dateSchema = dateSchema.notes(strArr); - dateSchema = dateSchema.tags(str); - dateSchema = dateSchema.tags(strArr); + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); - dateSchema = dateSchema.meta(obj); - dateSchema = dateSchema.example(obj); - dateSchema = dateSchema.unit(str); + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); - dateSchema = dateSchema.options(validOpts); - dateSchema = dateSchema.strict(); - dateSchema = dateSchema.concat(x); + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); - altSchema = dateSchema.when(str, whenOpts); - altSchema = dateSchema.when(ref, whenOpts); + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -546,50 +548,50 @@ numSchema = numSchema.positive(); numSchema = numSchema.negative(); namespace common { - numSchema = numSchema.allow(x); - numSchema = numSchema.allow(x, x); - numSchema = numSchema.allow([x, x, x]); - numSchema = numSchema.valid(x); - numSchema = numSchema.valid(x, x); - numSchema = numSchema.valid([x, x, x]); - numSchema = numSchema.only(x); - numSchema = numSchema.only(x, x); - numSchema = numSchema.only([x, x, x]); - numSchema = numSchema.equal(x); - numSchema = numSchema.equal(x, x); - numSchema = numSchema.equal([x, x, x]); - numSchema = numSchema.invalid(x); - numSchema = numSchema.invalid(x, x); - numSchema = numSchema.invalid([x, x, x]); - numSchema = numSchema.disallow(x); - numSchema = numSchema.disallow(x, x); - numSchema = numSchema.disallow([x, x, x]); - numSchema = numSchema.not(x); - numSchema = numSchema.not(x, x); - numSchema = numSchema.not([x, x, x]); + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); - numSchema = numSchema.default(x); + numSchema = numSchema.default(x); - numSchema = numSchema.required(); - numSchema = numSchema.optional(); - numSchema = numSchema.forbidden(); + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); - numSchema = numSchema.description(str); - numSchema = numSchema.notes(str); - numSchema = numSchema.notes(strArr); - numSchema = numSchema.tags(str); - numSchema = numSchema.tags(strArr); + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); - numSchema = numSchema.meta(obj); - numSchema = numSchema.example(obj); - numSchema = numSchema.unit(str); + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); - numSchema = numSchema.options(validOpts); - numSchema = numSchema.strict(); - numSchema = numSchema.concat(x); + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); - altSchema = numSchema.when(str, whenOpts); - altSchema = numSchema.when(ref, whenOpts); + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -655,50 +657,50 @@ objSchema = objSchema.optionalKeys(str, str); objSchema = objSchema.optionalKeys(strArr); namespace common { - objSchema = objSchema.allow(x); - objSchema = objSchema.allow(x, x); - objSchema = objSchema.allow([x, x, x]); - objSchema = objSchema.valid(x); - objSchema = objSchema.valid(x, x); - objSchema = objSchema.valid([x, x, x]); - objSchema = objSchema.only(x); - objSchema = objSchema.only(x, x); - objSchema = objSchema.only([x, x, x]); - objSchema = objSchema.equal(x); - objSchema = objSchema.equal(x, x); - objSchema = objSchema.equal([x, x, x]); - objSchema = objSchema.invalid(x); - objSchema = objSchema.invalid(x, x); - objSchema = objSchema.invalid([x, x, x]); - objSchema = objSchema.disallow(x); - objSchema = objSchema.disallow(x, x); - objSchema = objSchema.disallow([x, x, x]); - objSchema = objSchema.not(x); - objSchema = objSchema.not(x, x); - objSchema = objSchema.not([x, x, x]); + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); - objSchema = objSchema.default(x); + objSchema = objSchema.default(x); - objSchema = objSchema.required(); - objSchema = objSchema.optional(); - objSchema = objSchema.forbidden(); + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); - objSchema = objSchema.description(str); - objSchema = objSchema.notes(str); - objSchema = objSchema.notes(strArr); - objSchema = objSchema.tags(str); - objSchema = objSchema.tags(strArr); + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); - objSchema = objSchema.meta(obj); - objSchema = objSchema.example(obj); - objSchema = objSchema.unit(str); + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); - objSchema = objSchema.options(validOpts); - objSchema = objSchema.strict(); - objSchema = objSchema.concat(x); + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); - altSchema = objSchema.when(str, whenOpts); - altSchema = objSchema.when(ref, whenOpts); + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -732,8 +734,8 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']}); -strSchema = strSchema.guid({version: 'uuidv4'}); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); @@ -742,50 +744,50 @@ strSchema = strSchema.uppercase(); strSchema = strSchema.trim(); namespace common { - strSchema = strSchema.allow(x); - strSchema = strSchema.allow(x, x); - strSchema = strSchema.allow([x, x, x]); - strSchema = strSchema.valid(x); - strSchema = strSchema.valid(x, x); - strSchema = strSchema.valid([x, x, x]); - strSchema = strSchema.only(x); - strSchema = strSchema.only(x, x); - strSchema = strSchema.only([x, x, x]); - strSchema = strSchema.equal(x); - strSchema = strSchema.equal(x, x); - strSchema = strSchema.equal([x, x, x]); - strSchema = strSchema.invalid(x); - strSchema = strSchema.invalid(x, x); - strSchema = strSchema.invalid([x, x, x]); - strSchema = strSchema.disallow(x); - strSchema = strSchema.disallow(x, x); - strSchema = strSchema.disallow([x, x, x]); - strSchema = strSchema.not(x); - strSchema = strSchema.not(x, x); - strSchema = strSchema.not([x, x, x]); + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); - strSchema = strSchema.default(x); + strSchema = strSchema.default(x); - strSchema = strSchema.required(); - strSchema = strSchema.optional(); - strSchema = strSchema.forbidden(); + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); - strSchema = strSchema.description(str); - strSchema = strSchema.notes(str); - strSchema = strSchema.notes(strArr); - strSchema = strSchema.tags(str); - strSchema = strSchema.tags(strArr); + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); - strSchema = strSchema.meta(obj); - strSchema = strSchema.example(obj); - strSchema = strSchema.unit(str); + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); - strSchema = strSchema.options(validOpts); - strSchema = strSchema.strict(); - strSchema = strSchema.concat(x); + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); - altSchema = strSchema.when(str, whenOpts); - altSchema = strSchema.when(ref, whenOpts); + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -809,22 +811,22 @@ namespace validate_tests { Joi.validate(value, schema); Joi.validate(value, schema, validOpts); Joi.validate(value, schema, validOpts, (err, value) => { - x = value; - str = err.message; - str = err.details[0].path; - str = err.details[0].message; - str = err.details[0].type; + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { - x = value; - str = err.message; - str = err.details[0].path; - str = err.details[0].message; - str = err.details[0].type; + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; }); // variant Joi.validate(num, schema, validOpts, (err, value) => { - num = value; + num = value; }); // plain opts @@ -851,6 +853,11 @@ namespace validate_tests { returnValue = Joi.validate(value, obj, validOpts); value = Joi.validate(value, obj, validOpts, (err, value) => value); value = Joi.validate(value, schema, validOpts, (err, value) => value); + + returnValue = schema.validate(value); + returnValue = schema.validate(value, validOpts); + value = schema.validate(value, (err, value) => value); + value = schema.validate(value, validOpts, (err, value) => value); } } diff --git a/types/jpush-react-native/index.d.ts b/types/jpush-react-native/index.d.ts new file mode 100644 index 0000000000..d8b27e0b2c --- /dev/null +++ b/types/jpush-react-native/index.d.ts @@ -0,0 +1,122 @@ +// Type definitions for jpush-react-native 1.6 +// Project: https://github.com/jpush/jpush-react-native +// Definitions by: HuHuanming +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default class JPush { + /** + * Android only + * 初始化JPush 必须先初始化才能执行其他操作 + */ + static initPush(): void; + + /** + * Android + */ + static stopPush(): void; + + /** + * Android + */ + static resumePush(): void; + + /** + * Android + */ + static clearAllNotifications(): void; + + /** + * Android + */ + static clearNotificationById(id: string): void; + + /** + * Android + */ + static getInfo(cb: (map: any) => void): void; + + static setTags(tags: string[], successCallback: () => void, failedCallback: () => void): void; + + static setAlias(alias: string, successCallback: () => void, failedCallback: () => void): void; + + static setAliasAndTags(alias: string, tag: string[], successCallback: () => void, failedCallback: () => void): void; + + /** + * Android + */ + static setStyleBasic(): void; + + /** + * Android + */ + static setStyleCustom(): void; + + /** + * Android + */ + static addReceiveCustomMsgListener(cb: (message: string) => void): void; + + /** + * Android + */ + static removeReceiveCustomMsgListener(cb: any): void; + + /** + * Android + */ + static addReceiveNotificationListener(cb: (map: any) => void): void; + + /** + * Android + */ + static removeReceiveNotificationListener(cb: any): void; + + /** + * Android + */ + static addReceiveOpenNotificationListener(cb: (message: string) => void): void; + + /** + * Android + */ + static removeReceiveOpenNotificationListener(cb: any): void; + + /** + * Android + * If device register succeed, the server will return registrationId + */ + static addGetRegistrationIdListener(cb: (registrationId: string) => void): void; + + static removeGetRegistrationIdListener(cb: any): void; + + /** + * iOS, Android + */ + static getRegistrationID(cb: (registrationId: string) => void): void; + + /** + * iOS + */ + static setupPush(): void; + + /** + * iOS + */ + static getAppkeyWithcallback(cb: (appKey: string) => void): void; + + // iOS Only + static setLocalNotification( + date: Date, + alertBody: string, + badge?: number, + alertAction?: string, + notificationKey?: string, + userInfo?: any, + soundName?: string + ): void; + + /** + * iOS + */ + static setBadge(badge: number, callback: (badges: number[]) => void): void; +} diff --git a/types/jpush-react-native/jpush-react-native-tests.ts b/types/jpush-react-native/jpush-react-native-tests.ts new file mode 100644 index 0000000000..d1af013e11 --- /dev/null +++ b/types/jpush-react-native/jpush-react-native-tests.ts @@ -0,0 +1,77 @@ +import JPush from 'jpush-react-native'; + +JPush.initPush(); + +JPush.stopPush(); + +JPush.resumePush(); + +JPush.clearAllNotifications(); + +JPush.clearNotificationById('id'); + +JPush.getInfo((map) => {}); + +JPush.setTags( + ['tag1', 'tag2'], + () => {}, + () => {}, +); + +JPush.setAlias( + 'alias', + () => {}, + () => {}, +); + +JPush.setAliasAndTags( + 'alias', + ['tag1', 'tag2'], + () => { }, + () => { }, +); + +JPush.setStyleBasic(); + +JPush.setStyleCustom(); + +JPush.addReceiveCustomMsgListener(() => {}); + +JPush.removeReceiveCustomMsgListener(() => {}); + +JPush.addReceiveNotificationListener(() => {}); + +JPush.removeReceiveNotificationListener(() => {}); + +JPush.addReceiveOpenNotificationListener(() => {}); + +JPush.removeReceiveOpenNotificationListener(() => {}); + +JPush.addGetRegistrationIdListener((registrationId) => {}); + +JPush.removeGetRegistrationIdListener(() => {}); + +JPush.getRegistrationID((registrationId) => {}); + +JPush.setupPush(); + +JPush.getAppkeyWithcallback((appKey) => {}); + +JPush.setLocalNotification( + new Date(), + 'body', +); + +JPush.setLocalNotification( + new Date(), + 'body', + 2, + 'action', + 'key', + { + name: 'name', + }, + 'sound', +); + +JPush.setBadge(1, () => {}); diff --git a/types/jpush-react-native/tsconfig.json b/types/jpush-react-native/tsconfig.json new file mode 100644 index 0000000000..a789df247c --- /dev/null +++ b/types/jpush-react-native/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jpush-react-native-tests.ts" + ] +} diff --git a/types/jpush-react-native/tslint.json b/types/jpush-react-native/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/jpush-react-native/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jquery.growl/index.d.ts b/types/jquery.growl/index.d.ts new file mode 100644 index 0000000000..2a847b8ef7 --- /dev/null +++ b/types/jquery.growl/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for jquery.growl 1.3 +// Project: https://github.com/ksylvest/jquery-growl#readme +// Definitions by: Amir.h Yeganemehr +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace growl { + interface Options { + // Message + message: string; + // Title + title?: string; + // URL + url?: string; + // while hovering over the alert, prevent it from being dismissed (true | false - default: true) + delayOnHover?: boolean; + // the duration (in milliseconds) for which the alert is displayed (default: 3200) + duration?: number; + // whether the alert should be fixed rather than auto- dismissed(true | false - default: false) + fixed?: boolean; + // the alert's position ('tl' | 'tr' | 'bl' | 'br' | 'tc' | 'bc' - default: 'tr') + location?: string; + // the alert's size ('small' | 'medium' | 'large' - default: 'medium') + size?: string; + // the alert's style ('default' | 'error' | 'notice' | 'warning' - default: 'default') + style?: string; + } +} + +interface growl { + (options: growl.Options): void; + error(options: growl.Options): void; + notice(options: growl.Options): void; + warning(options: growl.Options): void; +} + +interface JQueryStatic { + growl: growl; +} diff --git a/types/jquery.growl/jquery.growl-tests.ts b/types/jquery.growl/jquery.growl-tests.ts new file mode 100644 index 0000000000..3391441bf1 --- /dev/null +++ b/types/jquery.growl/jquery.growl-tests.ts @@ -0,0 +1,4 @@ +$.growl({ title: "Growl", message: "The kitten is awake!" }); +$.growl.error({ message: "The kitten is attacking!" }); +$.growl.notice({ message: "The kitten is cute!" }); +$.growl.warning({ message: "The kitten is ugly!" }); diff --git a/types/jquery.growl/tsconfig.json b/types/jquery.growl/tsconfig.json new file mode 100644 index 0000000000..8eb3a19e35 --- /dev/null +++ b/types/jquery.growl/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.growl-tests.ts" + ] +} diff --git a/types/jquery.growl/tslint.json b/types/jquery.growl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jquery.growl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.validation/index.d.ts b/types/jquery.validation/index.d.ts index 9b77a80e23..5e0e2cfa01 100644 --- a/types/jquery.validation/index.d.ts +++ b/types/jquery.validation/index.d.ts @@ -10,7 +10,7 @@ declare namespace JQueryValidation { type ValidatePredicate = ((element: HTMLElement, event: JQueryEventObject) => void); - type ShouldValidatePredicate = boolean|ValidatePredicate; + type ShouldValidatePredicate = boolean | ValidatePredicate; interface ValidationOptions { /** @@ -218,7 +218,7 @@ declare namespace JQueryValidation { * * @param template The string to format. */ - format(template: string): ( (...args: any[]) => string); + format(template: string): ((...args: any[]) => string); format(template: string, ...args: any[]): string; /** * Modify default settings for validation. @@ -232,7 +232,7 @@ declare namespace JQueryValidation { } interface Validator { - element(element: string|JQuery): boolean; + element(element: string | JQuery): boolean; checkForm(): boolean; /** * Validates the form, returns true if it is valid, false otherwise. diff --git a/types/jquery.validation/jquery.validation-tests.ts b/types/jquery.validation/jquery.validation-tests.ts index 08bc439973..37273e0f51 100644 --- a/types/jquery.validation/jquery.validation-tests.ts +++ b/types/jquery.validation/jquery.validation-tests.ts @@ -15,8 +15,8 @@ function test_validate() { const errors = validator.numberOfInvalids(); if (errors) { const message = errors === 1 - ? 'You missed 1 field. It has been highlighted' - : 'You missed ' + errors + ' fields. They have been highlighted'; + ? 'You missed 1 field. It has been highlighted' + : 'You missed ' + errors + ' fields. They have been highlighted'; $("div.error span").html(message); $("div.error").show(); } else { @@ -56,7 +56,7 @@ function test_validate() { }, errorPlacement: (error, element) => { if (element.attr("name") === "fname" - || element.attr("name") === "lname") + || element.attr("name") === "lname") error.insertAfter("#lastname"); else error.insertAfter(element); @@ -84,7 +84,7 @@ function test_validate() { onclick: (elt) => { } }); $(".selector").validate({ - onfocusout: (elt, event) => { }, + onfocusout: (elt, event) => { }, onkeyup: (elt, event) => { }, onclick: (elt, event) => { } }); @@ -155,12 +155,12 @@ function test_validate() { highlight: (element: HTMLInputElement, errorClass, validClass) => { $(element).addClass(errorClass).removeClass(validClass); $(( element).form).find("label[for=" + element.id + "]") - .addClass(errorClass); + .addClass(errorClass); }, unhighlight: (element: HTMLInputElement, errorClass, validClass) => { $(element).removeClass(errorClass).addClass(validClass); $(( element).form).find("label[for=" + element.id + "]") - .removeClass(errorClass); + .removeClass(errorClass); } }); $(".selector").validate({ @@ -174,8 +174,8 @@ function test_validate() { onclick: false, }); $('.selector').validate({ - onfocusout: () => {}, - onkeyup: () => {}, + onfocusout: () => { }, + onkeyup: () => { }, onclick: elt => 2, }); } diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 0a47546193..ca799f21e5 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery 1.10.x / 2.0.x // Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink , Thomas Schulz +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink , Thomas Schulz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* ***************************************************************************** @@ -1657,6 +1657,14 @@ interface JQuery { * @see {@link https://api.jquery.com/css/#css-propertyName} */ css(propertyName: string): string; + /** + * Get the value of style properties for the first element in the set of matched elements. + * Results in an object of property-value pairs. + * + * @param propertyNames An array of one or more CSS properties. + * @see {@link https://api.jquery.com/css/#css-propertyNames} + */ + css(propertyNames: string[]): any; /** * Set one or more CSS properties for the set of matched elements. * @@ -2767,7 +2775,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, selector?: string, data?: any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * @@ -2775,7 +2783,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: any; }, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, data?: any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -3347,7 +3355,6 @@ interface JQuery { * @see {@link https://api.jquery.com/selector/} */ selector: string; - [index: string]: any; [index: number]: HTMLElement; /** diff --git a/types/js-schema/index.d.ts b/types/js-schema/index.d.ts index 8c332b8181..adccce7809 100644 --- a/types/js-schema/index.d.ts +++ b/types/js-schema/index.d.ts @@ -1,21 +1,23 @@ // Type definitions for js-schema // Project: https://github.com/molnarg/js-schema -// Definitions by: Marcin Porebski +// Definitions by: Marcin Porebski , Robin Labat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'js-schema' { - export interface Schema - { - (obj: any): boolean; // test obj against the schema + function schema(definition: any): schema.Schema; + + namespace schema { + interface Schema { + (obj: any): boolean; // test obj against the schema + } } - export default function schema(definition: any): Schema + export = schema; } -interface NumberConstructor -{ +interface NumberConstructor { min(n: number): NumberConstructor; max(n: number): NumberConstructor; below(n: number): NumberConstructor; @@ -23,28 +25,24 @@ interface NumberConstructor step(n: number): NumberConstructor; } -interface StringConstructor -{ +interface StringConstructor { of(charset: string): StringConstructor; of(length: number, charset: string): StringConstructor; of(minLength: number, maxLength: number, charset: string): StringConstructor; } -interface ArrayConstructor -{ +interface ArrayConstructor { like(arr: Array): ArrayConstructor; of(pattern: any): ArrayConstructor; of(length: number, pattern: any): ArrayConstructor; of(minLength: number, maxLength: number, pattern: any): ArrayConstructor; } -interface ObjectConstructor -{ +interface ObjectConstructor { like(obj: any): ObjectConstructor; reference(obj: any): ObjectConstructor; } -interface FunctionConstructor -{ +interface FunctionConstructor { reference(func: Function): FunctionConstructor; -} +} \ No newline at end of file diff --git a/types/js-schema/js-schema-tests.ts b/types/js-schema/js-schema-tests.ts index bb5098a434..028b860e0a 100644 --- a/types/js-schema/js-schema-tests.ts +++ b/types/js-schema/js-schema-tests.ts @@ -1,4 +1,4 @@ -import {default as schema} from 'js-schema'; +import * as schema from 'js-schema'; var Duck = schema({ // A duck swim : Function, // - can swim diff --git a/types/js-search/index.d.ts b/types/js-search/index.d.ts new file mode 100644 index 0000000000..49c10251eb --- /dev/null +++ b/types/js-search/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for js-search v1.4.0 +// Project: https://github.com/bvaughn/js-search +// Definitions by: Guo Yunhe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "js-search" { + + class Search { + + constructor( + uidFieldName: string | Array + ); + + public indexStrategy: IIndexStrategy; + public sanitizer: ISanitizer; + public searchIndex: ISearchIndex; + public tokenizer: ITokenizer; + + public addDocument(document: Object): void; + public addDocuments(documents: Array): void; + + public addIndex(field: string | Array): void; + + public search(query: string): Array; + + } + + interface IIndexStrategy { + expandToken(token: string): Array; + } + + class AllSubstringsIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class ExactWordIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class PrefixIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + interface ISanitizer { + sanitize(text: string): string; + } + + class CaseSensitiveSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + class LowerCaseSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + interface ISearchIndex { + indexDocument( + token: string, + uid: string, + document: Object + ): void; + + search( + tokens: Array, + corpus: Array + ): Array; + } + + type ITfIdfTokenMap = { + [token: string]: ITfIdfTokenMetadata; + }; + + type ITfIdfUidMap = { + [uid: string]: ITfIdfUidMetadata; + }; + + type ITfIdfTokenMetadata = { + $numDocumentOccurrences: number; + $totalNumOccurrences: number; + $uidMap: ITfIdfUidMap; + }; + + type ITfIdfUidMetadata = { + $document: Object; + $numTokenOccurrences: number; + }; + + class TfIdfSearchIndex implements ISearchIndex { + constructor(uidFieldName: string | Array); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + class UnorderedSearchIndex implements ISearchIndex { + constructor(); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + interface ITokenizer { + tokenize(text: string): Array; + } + + class SimpleTokenizer implements ITokenizer { + tokenize(text: string): Array; + } + + type StemmingFunction = (text: string) => string; + + class StemmingTokenizer implements ITokenizer { + constructor( + stemmingFunction: StemmingFunction, + decoratedTokenizer: ITokenizer + ); + + tokenize(text: string): Array; + } + + class StopWordsTokenizer implements ITokenizer { + constructor(decoratedTokenizer: ITokenizer); + + tokenize(text: string): Array; + } + + var StopWordsMap: any; + + class TokenHighlighter { + + constructor( + opt_indexStrategy: IIndexStrategy, + opt_sanitizer: ISanitizer, + opt_wrapperTagName: string + ); + + public highlight(text: string, tokens: Array): string; + + } + +} diff --git a/types/js-search/js-search-tests.ts b/types/js-search/js-search-tests.ts new file mode 100644 index 0000000000..b852e000cc --- /dev/null +++ b/types/js-search/js-search-tests.ts @@ -0,0 +1,58 @@ +import { Search, ITokenizer, StopWordsMap, StopWordsTokenizer, StemmingTokenizer, SimpleTokenizer, UnorderedSearchIndex } from "js-search"; + +var theGreatGatsby = { + isbn: '9781597226769', + title: 'The Great Gatsby', + author: { + name: 'F. Scott Fitzgerald' + }, + tags: ['book', 'inspirational'] +}; +var theDaVinciCode = { + isbn: '0307474275', + title: 'The DaVinci Code', + author: { + name: 'Dan Brown' + }, + tags: ['book', 'mystery'] +}; +var angelsAndDemons = { + isbn: '074349346X', + title: 'Angels & Demons', + author: { + name: 'Dan Brown', + }, + tags: ['book', 'mystery'] +}; + +var search = new Search('isbn'); +search.addIndex('title'); +search.addIndex(['author', 'name']); +search.addIndex('tags') + +search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]); + +search.search('The'); // [theGreatGatsby, theDaVinciCode] +search.search('scott'); // [theGreatGatsby] +search.search('dan'); // [angelsAndDemons, theDaVinciCode] +search.search('mystery') // [angelsAndDemons, theDaVinciCode] + +search.tokenizer = { + tokenize(text: any) { + // Convert text to an Array of strings and return the Array + } +}; + + +// Function should accept a string param and return a string +var stemmer = function () { return 'foobar' }; + +search.tokenizer = new StemmingTokenizer(stemmer, new SimpleTokenizer()); + + +search.tokenizer = new StopWordsTokenizer(new SimpleTokenizer()); + +StopWordsMap.the = false; // Do not treat "the" as a stop word +StopWordsMap.bob = true; // Treat "bob" as a stop word + +search.searchIndex = new UnorderedSearchIndex(); diff --git a/types/js-search/tsconfig.json b/types/js-search/tsconfig.json new file mode 100644 index 0000000000..83ce87381c --- /dev/null +++ b/types/js-search/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "js-search-tests.ts" + ] +} diff --git a/types/js-search/tslint.json b/types/js-search/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-search/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jui-core/index.d.ts b/types/jui-core/index.d.ts index 2bea574d7c..d8143aaa28 100644 --- a/types/jui-core/index.d.ts +++ b/types/jui-core/index.d.ts @@ -34,7 +34,7 @@ export interface UtilBase { * @param {Function} ctor base Class * @param {Function} superCtor super Class */ - inherit( ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any) ): void; + inherit(ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any)): void; /** * @method extend @@ -53,7 +53,7 @@ export interface UtilBase { * @param {String or Number} px * @return {Number} */ - pxToInt(px: string| number): number; + pxToInt(px: string | number): number; /** * @method clone @@ -145,7 +145,7 @@ export interface UtilBase { * @param {Number} dataSize * @return {String} 변환된 csv 문자열 */ - dataToCsv(keys: string[] , dataList: any[], dataSize: number): string; + dataToCsv(keys: string[], dataList: any[], dataSize: number): string; /** * @method dataToCsv2 @@ -268,7 +268,7 @@ export interface UtilBase { * @param {Object} [context=null] * @return {Function} 최적화된 루프 콜백 (index, groupIndex 2가지 파라미터를 받는다.) */ - loop(total: number, context?: any): ((index: number, groupIndex: number) => void ); + loop(total: number, context?: any): ((index: number, groupIndex: number) => void); /** * @method loopArray @@ -280,7 +280,7 @@ export interface UtilBase { * @param {Object} [context=null] * @return {Function} 최적화된 루프 콜백 (data, index, groupIndex 3가지 파라미터를 받는다.) */ - loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void ); + loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void); /** * @method makeIndex @@ -405,7 +405,7 @@ export interface JuiStatic { * @param {String} type Event type * @param {Array} args Event arguments */ - emit(key: string, type: string, args: any[]): void; + emit(key: string, type: string, args: any[]): void; /** * @method get @@ -414,7 +414,7 @@ export interface JuiStatic { * @param {Integer/String} key * @returns {Object/Array} UI instance */ - get(key: number|string): any; + get(key: number | string): any; /** * @method getAll @@ -422,7 +422,7 @@ export interface JuiStatic { * * @return {Array} UI instances */ - getAll(): any[]; + getAll(): any[]; /** * @method create @@ -433,7 +433,7 @@ export interface JuiStatic { * @param {Object} options * @return {Object} */ - create(type: string, selector: any, options?: {}): any; + create(type: string, selector: any, options?: {}): any; } export interface UICollection { @@ -455,7 +455,7 @@ export interface UICore { * @param {Function} args Event Arguments * @return {Mixed} */ - emit(type: string, args: () => void): any; + emit(type: string, args: () => void): any; /** * @method on @@ -464,7 +464,7 @@ export interface UICore { * @param {String} type Event type * @param {Function} callback */ - on(type: string, callback: () => void): void; + on(type: string, callback: () => void): void; /** * @method off @@ -472,7 +472,7 @@ export interface UICore { * * @param {String} type Event type */ - off(type: string): void; + off(type: string): void; /** * @method addValid @@ -481,7 +481,7 @@ export interface UICore { * @param {String} name Method name * @param {Array} params Parameters */ - addValid(name: string, params: any[]): void; + addValid(name: string, params: any[]): void; /** * @method callBefore @@ -491,7 +491,7 @@ export interface UICore { * @param {Function} callback * @return {Mixed} */ - callBefore(name: string, callback: () => void): void; + callBefore(name: string, callback: () => void): void; /** * @method callAfter @@ -501,7 +501,7 @@ export interface UICore { * @param {Function} callback * @return {Mixed} */ - callAfter(name: string, callback: () => void): void; + callAfter(name: string, callback: () => void): void; /** * @method callDelay @@ -510,7 +510,7 @@ export interface UICore { * @param {String} name Method name * @param {Function} callback */ - callDelay(name: string, callObj: () => void): void; + callDelay(name: string, callObj: () => void): void; /** * @method setTpl @@ -519,7 +519,7 @@ export interface UICore { * @param {String} name Template name * @param {String} html Template markup */ - setTpl(name: string, html: string): void; + setTpl(name: string, html: string): void; /** * @method setOption @@ -528,14 +528,14 @@ export interface UICore { * @param {String} key * @param {Mixed} value */ - setOption(key: string, value: any): void; + setOption(key: string, value: any): void; /** * @method destroy * Removes all events set in a UI obejct and the DOM element * */ - destroy(): void; + destroy(): void; } //noinspection TypeScriptUnresolvedVariable @@ -549,7 +549,7 @@ export interface UIEvent extends UICore { * @param {String/HTMLElement} Selector * @returns {*|jQuery} */ - find(selector: any): JQuery; + find(selector: any): JQuery; } export class ColorScale { @@ -807,7 +807,7 @@ export interface UtilMath { inverseMatrix3d(a: any[]): any[]; } -export interface UtilScaleOrdinal extends Function { +export interface UtilScaleOrdinal extends Function { (x: number): number; domain(values: any[]): UtilScaleOrdinal; range(values: any[]): UtilScaleOrdinal; diff --git a/types/jui-grid/index.d.ts b/types/jui-grid/index.d.ts index 8ced2164e4..5da7d23c43 100644 --- a/types/jui-grid/index.d.ts +++ b/types/jui-grid/index.d.ts @@ -3,16 +3,16 @@ // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {UIEvent} from 'jui-core'; +import { UIEvent } from 'jui-core'; export interface GridColumn { - (index: number|string): this; + (index: number | string): this; /** @property {HTMLElement} [element=null] TH element of a specified column */ element: any; /** @property {String} [order="asc"] Column sort state */ - order: "asc"|"desc"; + order: "asc" | "desc"; /** @property {String} [name=null] Column name */ name?: string; @@ -27,7 +27,7 @@ export interface GridColumn { index: number; /** @property {"show"/"hide"/"resize"} [type="show"] The current column state */ - type: "show"|"hide"|"resize"; + type: "show" | "hide" | "resize"; /** @property {Integer} [width=null] Column width */ width?: number; @@ -47,7 +47,7 @@ export interface GridRow { rownum?: number; /** @property {String/Integer} [index=null] Index of a specified row. In the case of a tree structure, a depth is given. */ - index: number|string; + index: number | string; /** @property {HTMLElement} [element=null] TR element of a specified row. */ element: any; @@ -68,12 +68,12 @@ export interface GridRow { depth: number; /** @property {"open"/"fold"} [type="fold"] State value that indicates whether a child row is shown or hidden. */ - type: "open"|"fold"; + type: "open" | "fold"; /** @property {Function} [type="null"] State value that indicates whether a child row is shown or hidden. */ tpl?(): void; - setIndex(rownum: number|string): void; + setIndex(rownum: number | string): void; reload(columns: GridColumn[], seq: any, xssFilter: any): void; destroy(): void; isLeaf(): boolean; @@ -81,37 +81,37 @@ export interface GridRow { open(): void; appendChild(row: GridRow): void; insertChild(rownum: number, row: GridRow, isReload?: any): void; - removeChild(index: number|string): void; + removeChild(index: number | string): void; lastChild(): GridRow; - lastChildLeaf(lastRow: GridRow): GridRow|any; + lastChildLeaf(lastRow: GridRow): GridRow | any; showCell(index: number): void; hideCell(index: number): void; } export interface GridBase { - appendRow(index: number|string, data?: {}): GridRow; - insertRow(index: number|string, data: {}): GridRow; - updateRow(index: number|string, data: {}): GridRow; - moveRow(index: number|string, targetIndex: number|string): void; - removeRow(index: number|string): void; - openRow(index: number|string): void; + appendRow(index: number | string, data?: {}): GridRow; + insertRow(index: number | string, data: {}): GridRow; + updateRow(index: number | string, data: {}): GridRow; + moveRow(index: number | string, targetIndex: number | string): void; + removeRow(index: number | string): void; + openRow(index: number | string): void; openRowAll(): void; - foldRow(index: number|string): void; + foldRow(index: number | string): void; foldRowAll(): void; removeRows(): void; sortRows(name: string, isDesc: boolean): void; appendColumn(tplType: string, dataList: any[]): void; - removeColumn(index: number|string): void; - hideColumn(index: number|string): void; - showColumn(index: number|string): void; + removeColumn(index: number | string): void; + hideColumn(index: number | string): void; + showColumn(index: number | string): void; getColumnCount(): number; getRowCount(): number; - getColumn(index?: number|string): GridColumn|GridColumn[]; - getRow(index?: number|string): GridRow|GridRow[]; - getRowAll(index: number|string): GridRow[]; - getRowParent(index: number|string): GridRow; - setColumn(index: number|string, column: GridColumn): void; - setRow(index: number|string, row: GridRow): void; + getColumn(index?: number | string): GridColumn | GridColumn[]; + getRow(index?: number | string): GridRow | GridRow[]; + getRowAll(index: number | string): GridRow[]; + getRowParent(index: number | string): GridRow; + setColumn(index: number | string, column: GridColumn): void; + setRow(index: number | string, row: GridRow): void; } export interface GridTable extends UIEvent { @@ -153,7 +153,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean/Array} [colshow=false] * Sets a column index shown when the Show/Hide Column menu is enabled. */ - colshow?: boolean|any[], + colshow?: boolean | any[], /** * @cfg {Boolean} [scroll=false] @@ -189,7 +189,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean|Array} [editRow=false] * Determines whether to use a modified row area. */ - editRow?: boolean|any[], + editRow?: boolean | any[], /** * @cfg {Boolean} [editEvent=true] @@ -207,7 +207,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean/Array} [sort=false] * Determines whether to use the table sort function. */ - sort?: boolean|any[], + sort?: boolean | any[], /** * @cfg {Integer} [sortIndex=null] @@ -219,7 +219,7 @@ export interface GridTable extends UIEvent { * @cfg {String} [sortOrder="asc"] * Determines whether to use the table sort function. */ - sortOrder?: "asc"|"desc", + sortOrder?: "asc" | "desc", /** * @cfg {Boolean} [sortEvent=true] @@ -242,7 +242,7 @@ export interface GridTable extends UIEvent { * * @param {Array} rows */ - update(indexOrRows?: any, rows?: any): void; + update(indexOrRows?: any, rows?: any): void; /** * @method updateTree * It is possible to configure a tree table using an object array with the index and data properties. @@ -257,7 +257,7 @@ export interface GridTable extends UIEvent { * * @param {RowObject} row */ - append(rowOrIndex?: number|any, row?: any): void; + append(rowOrIndex?: number | any, row?: any): void; /** * @method insert @@ -468,7 +468,7 @@ export interface GridTable extends UIEvent { * @param {"Integer"/"String"} key index or column key * @return {ColumnObject} column */ - getColumn(index: number|string): GridColumn; + getColumn(index: number | string): GridColumn; /** * @method showColumn @@ -476,7 +476,7 @@ export interface GridTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - showColumn(index: number|string, e?: any): void; + showColumn(index: number | string, e?: any): void; /** * @method hideColumn @@ -484,7 +484,7 @@ export interface GridTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - hideColumn(index: number|string, e?: any): void; + hideColumn(index: number | string, e?: any): void; /** * @method initColumns @@ -662,7 +662,7 @@ export interface GridXTable extends UIEvent { * * @param {Integer} index */ - open(index: number|string): void; + open(index: number | string): void; /** * @method fold @@ -670,19 +670,19 @@ export interface GridXTable extends UIEvent { * * @param {Integer} index */ - fold(index: number|string): void; + fold(index: number | string): void; /** * @method openAll * Shows all child rows of a specified index. */ - openAll(index: number|string): void; + openAll(index: number | string): void; /** * @method foldAll * Hides all child rows of a specified index. */ - foldAll(index: number|string): void; + foldAll(index: number | string): void; /** * @method next @@ -705,7 +705,7 @@ export interface GridXTable extends UIEvent { * @param {Integer} index * @param {String} order "asc" or "desc" */ - sort(index: number, order: "asc"|"desc", e?: any, isNotLoading?: any): void; + sort(index: number, order: "asc" | "desc", e?: any, isNotLoading?: any): void; /** * @method filter @@ -762,7 +762,7 @@ export interface GridXTable extends UIEvent { * @param {Integer|String} index * @param {Integer} dist */ - scrollTop(index: number|string, dist: number): void; + scrollTop(index: number | string, dist: number): void; /** * @deprecated @@ -831,7 +831,7 @@ export interface GridXTable extends UIEvent { * @param {"Integer"/"String"} key index or column key * @return {ColumnObject} column */ - getColumn(index: number|string): GridColumn; + getColumn(index: number | string): GridColumn; /** * @method getData @@ -840,7 +840,7 @@ export interface GridXTable extends UIEvent { * @param {"Integer"/"String"} key index * @return {ColumnObject} data */ - getData(index: number|string): any; + getData(index: number | string): any; /** * @method showColumn @@ -848,7 +848,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - showColumn(index: number|string): void; + showColumn(index: number | string): void; /** * @method hideColumn @@ -856,7 +856,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - hideColumn(index: number|string): void; + hideColumn(index: number | string): void; /** * @method initColumns @@ -864,7 +864,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - initColumns(keys: number|string): void; + initColumns(keys: number | string): void; /** * @method showColumnMenu @@ -973,7 +973,7 @@ export interface GridXTable extends UIEvent { * @param {Integer} columnIndex * @param {Function} callback */ - rowFunc(type: "sum"|"avg", index: number, callback: (data: any) => void): any; + rowFunc(type: "sum" | "avg", index: number, callback: (data: any) => void): any; /** * @method getPage diff --git a/types/jui/index.d.ts b/types/jui/index.d.ts index 24e5ed215c..93372f898d 100644 --- a/types/jui/index.d.ts +++ b/types/jui/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {UIEvent} from 'jui-core'; +import { UIEvent } from 'jui-core'; export interface UIAccordion extends UIEvent { (selector: any, options?: { @@ -26,7 +26,7 @@ export interface UIAccordion extends UIEvent { * */ multipanel?: boolean - }) : this; + }): this; /** * @method activeIndex @@ -52,7 +52,7 @@ export interface UIAutoComplete { * Designates words subject to autofill */ words?: string[] - }) : this; + }): this; /** * @method update @@ -61,14 +61,14 @@ export interface UIAutoComplete { * @param {Array} words * */ - update(newWords: string[]): void; + update(newWords: string[]): void; /** * @method close * Close the active drop-down * */ - close(): void; + close(): void; /** * @method list @@ -76,7 +76,7 @@ export interface UIAutoComplete { * * @return {Array} words */ - list(): string[]; + list(): string[]; } export interface UIColorPicker { @@ -85,11 +85,11 @@ export interface UIColorPicker { event?: any, type?: string, color?: string - }) : this; + }): this; - getColor(type: string): string|{}; + getColor(type: string): string | {}; - setColor(value: string|{}): void; + setColor(value: string | {}): void; } export interface UICombo { @@ -130,14 +130,14 @@ export interface UICombo { * @cfg {"top"/"bottom"} [position="bottom"] * It is possible to determine an initial selection button with a specified value */ - position?: "top"|"bottom", + position?: "top" | "bottom", /** * @cfg {Boolean} [flex=true] * Drop-down menu is varied by changing the width function */ flex?: boolean - }) : this; + }): this; /** * @method setIndex @@ -145,7 +145,7 @@ export interface UICombo { * * @param {Number} index */ - setIndex(index: number): void; + setIndex(index: number): void; /** * @method setValue @@ -153,7 +153,7 @@ export interface UICombo { * * @param {Mixed} value */ - setValue(value: any): void; + setValue(value: any): void; /** * @method getData @@ -161,7 +161,7 @@ export interface UICombo { * * @return {Object} */ - getData(): {}; + getData(): {}; /** * @method getValue @@ -169,7 +169,7 @@ export interface UICombo { * * @return {Mixed} */ - getValue(): any; + getValue(): any; /** * @method getText @@ -177,25 +177,25 @@ export interface UICombo { * * @return {String} */ - getText(): string; + getText(): string; /** * @method open * Shows the element list of a combo box */ - open(e: any): void; + open(e: any): void; /** * @method fold * Hides the element list of a combo box */ - fold(): void; + fold(): void; /** * @method reload * Re-defines a combo box */ - reload(): void; + reload(): void; } export interface UIDatePicker { @@ -206,7 +206,7 @@ export interface UIDatePicker { * @cfg {"daily"/"monthly"/"yearly"} [type="daily"] * Determines the type of a calendar */ - type?: "daily"|"monthly"|"yearly", + type?: "daily" | "monthly" | "yearly", /** * @cfg {String} [titleFormat="yyyy.MM"] @@ -224,7 +224,7 @@ export interface UIDatePicker { * @cfg {Date} [date="now"] * Selects a specific date as a basic */ - date?: "now"|Date, + date?: "now" | Date, /** * @cfg {Date} [minDate="null"] @@ -237,7 +237,7 @@ export interface UIDatePicker { * Selects a specific maximum date */ maxDate?: Date - }) : this; + }): this; /** * @method page @@ -246,7 +246,7 @@ export interface UIDatePicker { * @param {Integer} year * @param {Integer} month */ - page(y: number, m: number): void; + page(y: number, m: number): void; /** * @method prev @@ -260,7 +260,7 @@ export interface UIDatePicker { * Outputs a calendar that fits the next year/month * */ - next(e: any, moveYear?: boolean): void; + next(e: any, moveYear?: boolean): void; /** * @method select @@ -268,7 +268,7 @@ export interface UIDatePicker { * * @param {"year"/"month"/"date"/"timestamp"/"Date"} */ - select( ...args: any[]): void; + select(...args: any[]): void; /** * @method addTime @@ -276,7 +276,7 @@ export interface UIDatePicker { * * @param {"Integer"/"Date"} time Timestamp or Date */ - addTime(time: number|Date): void; + addTime(time: number | Date): void; /** * @method getDate @@ -284,7 +284,7 @@ export interface UIDatePicker { * * @return {Date} Date object */ - getDate(): Date; + getDate(): Date; /** * @method getTime @@ -292,7 +292,7 @@ export interface UIDatePicker { * * @return {Integer} Timestamp */ - getTime(): number; + getTime(): number; /** * @method getFormat @@ -300,13 +300,13 @@ export interface UIDatePicker { * * @return {String} format Formatted date string */ - getFormat(format: string): string; + getFormat(format: string): string; /** * @method reload * Reloads the datepicker */ - reload(): void; + reload(): void; } export interface UIDropdown { @@ -377,7 +377,7 @@ export interface UIDropdown { * @param {Integer} x * @param {Integer} y */ - show(x: number, y: number): void; + show(x: number, y: number): void; /** * @method move @@ -386,13 +386,13 @@ export interface UIDropdown { * @param {Integer} x * @param {Integer} y */ - move(x: number, y: number): void; + move(x: number, y: number): void; /** * @method reload * Reloads the dropdown list */ - reload(): void; + reload(): void; } export interface UIModal { @@ -403,7 +403,7 @@ export interface UIModal { * @cfg {"black"/"gray"} [color="black"] * Determines the color of a modal */ - color?: "black"|"gray", + color?: "black" | "gray", /** * @cfg {Float} [opacity=0.4] @@ -415,7 +415,7 @@ export interface UIModal { * @cfg {String/DOMElement} [target="body"] * Sets a selector on which a modal is shown */ - target?: string|any, + target?: string | any, /** * @cfg {Integer} [index=0] @@ -434,19 +434,19 @@ export interface UIModal { * Automatically hides a modal when clicking on it */ autoHide?: boolean - }): this; + }): this; /** * @method hide * Hides a modal */ - hide(): void; + hide(): void; /** * @method show * Shows a modal */ - show(): void; + show(): void; /** * @method resize @@ -463,7 +463,7 @@ export interface UINotify { * @cfg {"top"/"top-lefet"/"top-right"/"bottom"/"bottom-left"/"bottom-right"} [position="top-right"] * Designates the location where a notice message is added */ - position?: "top"|"top-lefet"|"top-right"|"bottom"|"bottom-left"|"bottom-right", + position?: "top" | "top-lefet" | "top-right" | "bottom" | "bottom-left" | "bottom-right", /** * @cfg {Integer} [padding=12] @@ -524,7 +524,7 @@ export interface UINotify { reset(): void; } -export interface UIPaging { +export interface UIPaging { (selector: any, options?: { tpl?: any, event?: any, @@ -593,7 +593,7 @@ export interface UIProgress { tpl?: any, event?: any, type?: "simple" | "flat", // simple or flat - orient?: "horizontal"|"vertical", // or vertical, + orient?: "horizontal" | "vertical", // or vertical, min?: number, max?: number, value?: number, @@ -618,7 +618,7 @@ export interface UIProperty { loadItems(newItems: any[]): void; - addItem(item: {}|any[]): void; + addItem(item: {} | any[]): void; // remove item by key or title removeItem(item: {}): void; @@ -628,7 +628,7 @@ export interface UIProperty { * * get a list of group's title. */ - getGroupList(): any[]; + getGroupList(): any[]; /** * @method collapsed @@ -637,7 +637,7 @@ export interface UIProperty { * * @param {String} id */ - collapsed(id: string): void; + collapsed(id: string): void; /** * @method expanded @@ -683,13 +683,13 @@ export interface UISelect { event?: any, items?: any[], placeholder?: string, - align?: 'left'|'right', - valign?: 'top'|'bottom', + align?: 'left' | 'right', + valign?: 'top' | 'bottom', multi?: boolean }): this; - setValue(value: any|any[]): void; - getValue(): any| any[]; + setValue(value: any | any[]): void; + getValue(): any | any[]; setSelectedIndex(index: number): void; getSelectedIndex(): number; update(data: any[]): void; @@ -699,8 +699,8 @@ export interface UISlider { (selector: any, options?: { tpl?: any, event?: any, - type?: "single"|"double", // or double - orient?: "horizontal"|"vertical", // or vertical, + type?: "single" | "double", // or double + orient?: "horizontal" | "vertical", // or vertical, min?: number, max?: number, step?: number, @@ -776,13 +776,13 @@ export interface UISplitter { * @cfg {"vertical"/"horizontal"} [direction='vertical'] * set bar's direction */ - direction?: 'vertical'|'horizontal', + direction?: 'vertical' | 'horizontal', /** * @cfg {String/Number} [initSize='50%'] * set first panel's default width or height */ - initSize?: string|number, + initSize?: string | number, /** * @cfg {Number/Array} [minSize=30] @@ -794,7 +794,7 @@ export interface UISplitter { * minSize[1] is second panel's minimum size * */ - minSize?: number|number[], + minSize?: number | number[], /** * @cfg {String} [items=[]] @@ -846,7 +846,7 @@ export interface UITab { * @cfg {String/DOMElement} [target=""] * Determines a selector in the area to become the content of a tab */ - target?: string|any, + target?: string | any, /** * @cfg {Integer} [index=0] @@ -963,7 +963,7 @@ export interface UITooltip { * @cfg {"top"/"bottom"/"left"/"right"} [position="top"] * Determines the location where a tooltip is shown */ - position?: "top"|"bottom"|"left"|"right", + position?: "top" | "bottom" | "left" | "right", /** * @cfg {Integer} [width=150] @@ -975,7 +975,7 @@ export interface UITooltip { * @cfg {"left"/"right"/"center"} [align="left"] * Determines the alignment state inside a tooltip */ - align?: "left"|"right"|"center", + align?: "left" | "right" | "center", /** * @cfg {Integer} [delay=0] @@ -1260,25 +1260,25 @@ export interface UIWindow { * @cfg {String/Integer} [left="auto"] * Determines the X coordinate of a window */ - left?: string|number, + left?: string | number, /** * @cfg {String/Integer} [top="auto"] * Determines the Y coordinate of a window */ - top?: string|number, + top?: string | number, /** * @cfg {String/Integer} [right="auto"] * Determines the X coordinate based on the right side of a window */ - right?: string|number, + right?: string | number, /** * @cfg {String/Integer} [bottom="auto"] * Determines the Y coordinate based on the bottom side of a window */ - bottom?: string|number, + bottom?: string | number, /** * @cfg {Boolean} [modal=false] diff --git a/types/kdbush/index.d.ts b/types/kdbush/index.d.ts new file mode 100644 index 0000000000..fa1581d09c --- /dev/null +++ b/types/kdbush/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for kdbush 1.0 +// Project: https://github.com/mourner/kdbush +// Definitions by: DenisCarriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type Points = number[][]; +type Get = (point: T) => number; +type ArrayType = typeof Int32Array | typeof Array; + +declare class KDBush { + ids: number[]; + coords: number[]; + nodeSize: number; + points: T[]; + range(minX: number, minY: number, maxX: number, maxY: number): number[]; + within(x: number, y: number, r: number): number[]; +} + +interface KDBushStatic { + (points: Points): KDBush; + (points: T[], getX: Get, getY: Get, nodeSize?: number, ArrayType?: ArrayType): KDBush; +} + +declare const kdbush: KDBushStatic; +declare namespace kdbush {} +export = kdbush; diff --git a/types/kdbush/kdbush-tests.ts b/types/kdbush/kdbush-tests.ts new file mode 100644 index 0000000000..c9fd8ae11f --- /dev/null +++ b/types/kdbush/kdbush-tests.ts @@ -0,0 +1,35 @@ +import * as kdbush from 'kdbush'; + +// API +const points = [[110, 60], [130, 40]]; +const index = kdbush(points); + +// properties +index.nodeSize; +index.points; +index.ids; +index.coords; + +// range +index.range(10, 10, 20, 20); +index.range(10, 10, 20, 20).map(id => points[id]); + +// within +index.within(10, 10, 5); +index.within(10, 10, 5).map(id => points[id]); + +// custom points (object) +const xy = [{x: 110, y: 60}, {x: 130, y: 40}]; +const index2 = kdbush(xy, p => p.x, p => p.y); +index2.points[0].x; +index2.points[0].y; +index2.points.map(p => [p.x, p.y]); + +// custom points (latlng) +const latlng = [[60, 110], [40, 130]]; +kdbush(latlng, p => p[1], p => p[0]); +kdbush(latlng, p => p[1], p => p[0], 64, Int32Array); + +// z coordinate (does not require Get callbacks) +const pointsZ = [[110, 60, 4000], [130, 40, 3000]]; +kdbush(pointsZ); diff --git a/types/kdbush/tsconfig.json b/types/kdbush/tsconfig.json new file mode 100644 index 0000000000..16814b627e --- /dev/null +++ b/types/kdbush/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "kdbush-tests.ts" + ] +} diff --git a/types/kdbush/tslint.json b/types/kdbush/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kdbush/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index f1d3fa0437..9848335e49 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -5409,6 +5409,7 @@ declare namespace kendo.ui { slotByElement(element: Element): any; slotByElement(element: JQuery): any; view(type?: string): void; + view(): kendo.ui.SchedulerView; viewName(): string; } @@ -5627,7 +5628,8 @@ declare namespace kendo.ui { dateHeaderTemplate?: string|Function; dayTemplate?: string|Function; editable?: boolean|SchedulerViewEditable; - endTime?: Date; + endDate?(): Date; + endTime?: Date; eventHeight?: number; eventTemplate?: string|Function; eventTimeTemplate?: string|Function; @@ -5641,6 +5643,7 @@ declare namespace kendo.ui { selectedShortDateFormat?: string; showWorkHours?: boolean; slotTemplate?: string|Function; + startDate?(): Date; startTime?: Date; title?: string; type?: string; diff --git a/types/keytar/index.d.ts b/types/keytar/index.d.ts index 5a27c0c984..f807b19a9f 100644 --- a/types/keytar/index.d.ts +++ b/types/keytar/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for keytar 3.0.2 +// Type definitions for keytar 4.0.2 // Project: http://atom.github.io/node-keytar/ -// Definitions by: Milan Burda , Brendan Forster +// Definitions by: Milan Burda , Brendan Forster , Hari Juturu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,9 +10,9 @@ * @param service The string service name. * @param account The string account name. * - * @returns the string password or null on failures. + * @returns A promise for the password string. */ -export declare function getPassword(service: string, account: string): string | null; +export declare function getPassword(service: string, account: string): Promise; /** * Add the password for the service and account to the keychain. @@ -21,9 +21,9 @@ export declare function getPassword(service: string, account: string): string | * @param account The string account name. * @param password The string password. * - * @returns true on success, false on failure. + * @returns A promise for the set password completion. */ -export declare function addPassword(service: string, account: string, password: string): boolean; +export declare function setPassword(service: string, account: string, password: string): Promise; /** * Delete the stored password for the service and account. @@ -31,29 +31,15 @@ export declare function addPassword(service: string, account: string, password: * @param service The string service name. * @param account The string account name. * - * @returns true on success, false on failure + * @returns A promise for the deletion status. True on success. */ -export declare function deletePassword(service: string, account: string): boolean; - -/** - * Replace the password for the service and account in the keychain. - * - * This is a simple convenience function that internally calls deletePassword(service, account) - * followed by addPassword(service, account, password). - * - * @param service The string service name. - * @param account The string account name. - * @param password The string password. - * - * @returns true on success, false on failure. - */ -export declare function replacePassword(service: string, account: string, password: string): boolean; +export declare function deletePassword(service: string, account: string): Promise; /** * Find a password for the service in the keychain. * * @param service The string service name. * - * @returns the string password or null on failures. + * @returns A promise for the password string. */ -export declare function findPassword(service: string): string | null; +export declare function findPassword(service: string): Promise; diff --git a/types/keytar/keytar-tests.ts b/types/keytar/keytar-tests.ts index d523050650..f6873838c2 100644 --- a/types/keytar/keytar-tests.ts +++ b/types/keytar/keytar-tests.ts @@ -1,13 +1,13 @@ import keytar = require('keytar'); -let success: boolean = false; +let setResult: Promise; +setResult = keytar.setPassword('keytar-tests', 'username', 'password'); -success = keytar.addPassword('keytar-tests', 'username', 'password'); +let success: Promise; success = keytar.deletePassword('keytar-tests', 'username'); -success = keytar.replacePassword('keytar-tests', 'username', 'password'); -let password: string = ''; +let password: Promise; password = keytar.findPassword('keytar-tests'); password = keytar.getPassword('keytar-tests', 'username'); diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 5e926679b1..16330b4e3a 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -22,7 +22,7 @@ interface Knex extends Knex.QueryInterface { __knex__: string; raw: Knex.RawBuilder; - transaction: (transactionScope: ((trx: Knex.Transaction) => void)) => Promise; + transaction(transactionScope: (trx: Knex.Transaction) => any): Promise; destroy(callback: Function): void; destroy(): Promise; batchInsert(tableName : TableName, data: any[], chunkSize : number) : Knex.QueryBuilder; @@ -64,6 +64,11 @@ declare namespace Knex { fullOuterJoin: Join; crossJoin: Join; + // Withs + with: With; + withRaw: WithRaw; + withWrapped: WithWrapped; + // Wheres where: Where; andWhere: Where; @@ -168,6 +173,7 @@ declare namespace Knex { interface Join { (raw: Raw): QueryBuilder; + (builder: QueryBuilder, clause: (this: JoinClause) => void): QueryBuilder; (tableName: string, columns: { [key: string]: string | number | Raw }): QueryBuilder; (tableName: string, callback: Function): QueryBuilder; (tableName: TableName, raw: Raw): QueryBuilder; @@ -203,6 +209,18 @@ declare namespace Knex { (tableName: string, binding?: Value): QueryBuilder; } + interface With extends WithRaw, WithWrapped { + } + + interface WithRaw { + (alias: string, raw: Raw): QueryBuilder; + (alias: string, sql: string, bindings?: Value[] | Object): QueryBuilder; + } + + interface WithWrapped { + (alias: string, callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; + } + interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; (callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; @@ -330,10 +348,10 @@ declare namespace Knex { exec(callback: Function): QueryBuilder; } - interface Transaction extends QueryBuilder { - commit: any; - rollback: any; - raw: Knex.RawBuilder; + interface Transaction extends Knex { + savepoint(transactionScope: (trx: Transaction) => any): Promise; + commit(value?: any): QueryBuilder; + rollback(error?: any): QueryBuilder; } // diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 67b07f263b..920b347a70 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -315,6 +315,29 @@ knex('accounts').where('activated', false).delete(); knex('accounts').where('activated', false).delete('id'); knex('accounts').where('activated', false).delete(['id', 'title']); +knex.with('old_books', function(qb) { + qb.select('*').from('books').where('published_date', '<', 1970); +}).select('*').from('old_books'); + +knex.with('new_books', knex.raw('select * from books where published_date >= 2016')) + .select('*').from('new_books'); + +knex.with('new_books', 'select * from books where published_date >= :year', { year: 2016 }) + .select('*').from('new_books'); + +knex.with('new_books', 'select * from books where published_date >= ?', [2016]) + .select('*').from('new_books'); + +knex.withRaw('recent_books', 'select * from books where published_date >= :year', { year: 2013 }) + .select('*').from('recent_books'); + +knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) + .select('*').from('recent_books'); + +knex.withWrapped("antique_books", function (qb) { + qb.select('*').from('books').where('published_date', '<', 1899); +}).select('*').from('antique_books'); + var someExternalMethod: Function; knex.transaction(function(trx) { @@ -411,7 +434,19 @@ knex.transaction(function(trx) { // Using trx as a transaction object: knex.transaction(function(trx) { - trx.raw('') + trx.raw(''); + + trx.on('query-error', function(error: Error) { + console.error(error); + }); + + trx.savepoint(function(nestedTrx) { + nestedTrx.rollback(new Error('something went terribly wrong')); + }); + + trx.transaction(function(nestedTrx) { + nestedTrx.commit(); + }); var info: any; var books: any[] = [ diff --git a/types/koa-generic-session/index.d.ts b/types/koa-generic-session/index.d.ts new file mode 100644 index 0000000000..f3a84e7b20 --- /dev/null +++ b/types/koa-generic-session/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for koa-generic-session 1.x +// Project: https://github.com/koajs/generic-session +// Definitions by: Nick Simmons +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Koa from "koa"; + +declare namespace koaSession { + interface Session { + cookie: any; + } + + interface SessionIdStore { + get(): any; + set(sid: string, session: Session): void; + reset(): void; + } + + interface SessionStore { + (): SessionStore; + get(sid: string): any; + set(sid: string, session: Session, ttl: number): void; + destroy(sid: string): void; + } + + interface SessionOptions { + key?: string; + store?: SessionStore; + ttl?: number; + prefix?: string; + cookie?: { + path?: string; + rewrite?: boolean; + signed?: boolean; + maxAge?: number; + secure?: boolean; + httpOnly?: boolean; + }; + allowEmpty?: boolean; + defer?: boolean; + reconnectTimeout?: number; + rolling?: boolean; + sessionIdStore?: SessionIdStore; + genSid?(length: number): string; + errorHandler?(error: Error, type: string, ctx: Koa.Context): void; + valid?(ctx: Koa.Context, session: Session): boolean; + beforeSave?(ctx: Koa.Context, session: Session): void; + } + + const MemoryStore: SessionStore; +} + +declare function koaSession(options: koaSession.SessionOptions): Koa.Middleware; +export = koaSession; diff --git a/types/koa-generic-session/koa-generic-session-tests.ts b/types/koa-generic-session/koa-generic-session-tests.ts new file mode 100644 index 0000000000..fb8d69b0e0 --- /dev/null +++ b/types/koa-generic-session/koa-generic-session-tests.ts @@ -0,0 +1,35 @@ +import * as Koa from "koa"; +import {MemoryStore, Session} from "koa-generic-session"; +import session = require("koa-generic-session"); + +const app = new Koa(); + +app.use(session({ + key: 'sessionKey', + store: MemoryStore(), + ttl: 60 * 60, + prefix: 'a-prefix', + cookie: { + path: '/test', + rewrite: false, + signed: false, + maxAge: 60 * 60, + secure: true, + httpOnly: true, + }, + allowEmpty: false, + defer: false, + reconnectTimeout: 100, + rolling: false, + sessionIdStore: { + get: () => 'something', + set: (sid: string, session: Session) => {}, + reset: () => {} + }, + genSid: (length: number) => 'aSid', + errorHandler: (error: Error, type: string, ctx: Koa.Context) => {}, + valid: (ctx: Koa.Context, session: Session) => true, + beforeSave: (ctx: Koa.Context, session: Session) => {} +})); + +app.listen(80); diff --git a/types/koa-generic-session/tsconfig.json b/types/koa-generic-session/tsconfig.json new file mode 100644 index 0000000000..b4cf43dab8 --- /dev/null +++ b/types/koa-generic-session/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-generic-session-tests.ts" + ] +} \ No newline at end of file diff --git a/types/koa-generic-session/tslint.json b/types/koa-generic-session/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/koa-generic-session/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/koa-helmet/index.d.ts b/types/koa-helmet/index.d.ts new file mode 100644 index 0000000000..f97480f505 --- /dev/null +++ b/types/koa-helmet/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for koa-helmet 3.1 +// Project: https://github.com/venables/koa-helmet#readme +// Definitions by: Nick Simmons +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { + IHelmetConfiguration, + IHelmetFrameguardConfiguration, + IHelmetHstsConfiguration, + IHelmetXssFilterConfiguration, + IHelmetDnsPrefetchControlConfiguration, + IHelmetHpkpConfiguration, + IHelmetReferrerPolicyConfiguration } from 'helmet'; +import {Middleware, Context} from 'koa'; + +declare namespace koaHelmet { + type KoaHelmetContentSecurityPolicyDirectiveFunction = (ctx: Context) => string; + + type KoaHelmetCspDirectiveValue = string | KoaHelmetContentSecurityPolicyDirectiveFunction; + + interface KoaHelmetContentSecurityPolicyDirectives { + baseUri?: KoaHelmetCspDirectiveValue[]; + childSrc?: KoaHelmetCspDirectiveValue[]; + connectSrc?: KoaHelmetCspDirectiveValue[]; + defaultSrc?: KoaHelmetCspDirectiveValue[]; + fontSrc?: KoaHelmetCspDirectiveValue[]; + formAction?: KoaHelmetCspDirectiveValue[]; + frameAncestors?: KoaHelmetCspDirectiveValue[]; + frameSrc?: KoaHelmetCspDirectiveValue[]; + imgSrc?: KoaHelmetCspDirectiveValue[]; + mediaSrc?: KoaHelmetCspDirectiveValue[]; + objectSrc?: KoaHelmetCspDirectiveValue[]; + pluginTypes?: KoaHelmetCspDirectiveValue[]; + reportUri?: string; + sandbox?: KoaHelmetCspDirectiveValue[]; + scriptSrc?: KoaHelmetCspDirectiveValue[]; + styleSrc?: KoaHelmetCspDirectiveValue[]; + } + + interface KoaHelmetContentSecurityPolicyConfiguration { + reportOnly?: boolean; + setAllHeaders?: boolean; + disableAndroid?: boolean; + browserSniff?: boolean; + directives?: KoaHelmetContentSecurityPolicyDirectives; + } + + interface KoaHelmet { + (options?: IHelmetConfiguration): Middleware; + contentSecurityPolicy(options?: KoaHelmetContentSecurityPolicyConfiguration): Middleware; + dnsPrefetchControl(options?: IHelmetDnsPrefetchControlConfiguration): Middleware; + frameguard(options?: IHelmetFrameguardConfiguration): Middleware; + hpkp(options?: IHelmetHpkpConfiguration): Middleware; + hsts(options?: IHelmetHstsConfiguration): Middleware; + ieNoOpen(): Middleware; + noCache(options?: any): Middleware; + noSniff(): Middleware; + referrerPolicy(options?: IHelmetReferrerPolicyConfiguration): Middleware; + xssFilter(options?: IHelmetXssFilterConfiguration): Middleware; + } +} + +declare const koaHelmet: koaHelmet.KoaHelmet; +export = koaHelmet; diff --git a/types/koa-helmet/koa-helmet-tests.ts b/types/koa-helmet/koa-helmet-tests.ts new file mode 100644 index 0000000000..1f50ea5c6b --- /dev/null +++ b/types/koa-helmet/koa-helmet-tests.ts @@ -0,0 +1,197 @@ +import * as Koa from 'koa'; +import helmet = require('koa-helmet'); + +const app = new Koa(); + +/** + * @summary Test for {@see helmet}. + */ +function helmetTest() { + app.use(helmet()); + app.use(helmet({})); + app.use(helmet({ frameguard: false })); + app.use(helmet({ frameguard: true })); + app.use(helmet({ + frameguard: { + action: 'deny' + } + })); +} + +/** + * @summary Test for {@see helmet#contentSecurityPolicy} function. + */ +function contentSecurityPolicyTest() { + const emptyArray: string[] = []; + const config = { + directives: { + baseUri: ['base.example.com'], + childSrc: ['child.example.com'], + connectSrc: ['connect.example.com'], + defaultSrc: ['*'], + fontSrc: ['font.example.com'], + formAction: ['formaction.example.com'], + frameAncestors: ["'none'"], + frameSrc: emptyArray, + imgSrc: ['images.example.com'], + mediaSrc: ['media.example.com'], + objectSrc: ['objects.example.com'], + pluginTypes: emptyArray, + reportUri: '/some-url', + sandbox: emptyArray, + scriptSrc: ['scripts.example.com', (ctx: Koa.Context) => { + return "'nonce-abc123'"; + }], + styleSrc: ['css.example.com'] + }, + reportOnly: false, + setAllHeaders: false, + disableAndroid: false + }; + + app.use(helmet.contentSecurityPolicy()); + app.use(helmet.contentSecurityPolicy({})); + app.use(helmet.contentSecurityPolicy(config)); + app.use(helmet.contentSecurityPolicy({ + directives: { + defaultSrc: ["'self'"] + }, + setAllHeaders: true + })); +} + +/** + * @summary Test for {@see helmet#dnsPrefetchControl} function. + */ +function dnsPrefetchControlTest() { + app.use(helmet.dnsPrefetchControl()); + app.use(helmet.dnsPrefetchControl({ allow: false })); + app.use(helmet.dnsPrefetchControl({ allow: true })); +} + +/** + * @summary Test for {@see helmet#frameguard} function. + */ +function frameguardTest() { + app.use(helmet.frameguard()); + app.use(helmet.frameguard({})); + app.use(helmet.frameguard({ action: 'deny' })); + app.use(helmet.frameguard({ action: 'sameorigin' })); + app.use(helmet.frameguard({ + action: 'allow-from', + domain: 'http://example.com' + })); +} + +/** + * @summary Test for {@see helmet#hpkp} function. + */ +function hpkpTest() { + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: false + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportUri: 'http://example.com' + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportOnly: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + setIf: (req, res) => true + })); +} + +/** + * @summary Test for {@see helmet#hsts} function. + */ +function hstsTest() { + app.use(helmet.hsts()); + + app.use(helmet.hsts({ maxAge: 7776000000 })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + includeSubdomains: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + preload: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + force: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + setIf: (req, res) => true + })); +} + +/** + * @summary Test for {@see helmet#ieNoOpen} function. + */ +function ieNoOpenTest() { + app.use(helmet.ieNoOpen()); +} + +/** + * @summary Test for {@see helmet#noCache} function. + */ +function noCacheTest() { + app.use(helmet.noCache()); + app.use(helmet.noCache({})); + app.use(helmet.noCache({ noEtag: true })); +} + +/** + * @summary Test for {@see helmet#noSniff} function. + */ +function noSniffTest() { + app.use(helmet.noSniff()); +} + +/** + * @summary Test for {@see helmet#referrerPolicy} function. + */ +function referrerPolicyTest() { + app.use(helmet.referrerPolicy({ policy: 'same-origin' })); +} + +/** + * @summary Test for {@see helmet#xssFilter} function. + */ +function xssFilterTest() { + app.use(helmet.xssFilter()); + app.use(helmet.xssFilter({})); + app.use(helmet.xssFilter({ setOnOldIE: false })); + app.use(helmet.xssFilter({ setOnOldIE: true })); +} diff --git a/types/koa-helmet/tsconfig.json b/types/koa-helmet/tsconfig.json new file mode 100644 index 0000000000..53162f08e8 --- /dev/null +++ b/types/koa-helmet/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-helmet-tests.ts" + ] +} diff --git a/types/koa-helmet/tslint.json b/types/koa-helmet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-helmet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-jwt/index.d.ts b/types/koa-jwt/index.d.ts index 4c123ff4a8..52836a6dce 100644 --- a/types/koa-jwt/index.d.ts +++ b/types/koa-jwt/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for koa-jwt 2.1 +// Type definitions for koa-jwt 3.2 // Project: https://github.com/koajs/jwt // Definitions by: Bruno Krebs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,7 +11,7 @@ declare function jwt(options: jwt.Options): jwt.Middleware; declare namespace jwt { interface Options { - secret: string | Buffer; + secret: string | Buffer | jwt.SecretProvider; key?: string; getToken?(opts: jwt.Options): string; passthrough?: boolean; @@ -30,4 +30,12 @@ declare namespace jwt { type Middleware = Koa.Middleware & { unless(options?: jwt.UnlessOptions): any; }; + + type SecretProvider = (header: jwt.TokenHeader) => Promise; + + interface TokenHeader { + alg: string; + kid: string; + typ: string; + } } diff --git a/types/koa-jwt/koa-jwt-tests.ts b/types/koa-jwt/koa-jwt-tests.ts index 646bb6d826..cdfc25fffa 100644 --- a/types/koa-jwt/koa-jwt-tests.ts +++ b/types/koa-jwt/koa-jwt-tests.ts @@ -15,3 +15,9 @@ app.use(jwt({ app.use(jwt({ secret: 'some-secret-key' }).unless({method: 'OPTIONS'})); + +app.use(jwt({ + secret: (header: jwt.TokenHeader): Promise => { + return Promise.resolve("some-secret-key"); + } +})); diff --git a/types/koa-redis/index.d.ts b/types/koa-redis/index.d.ts new file mode 100644 index 0000000000..94937c6455 --- /dev/null +++ b/types/koa-redis/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for koa-redis 3.0 +// Project: https://github.com/koajs/koa-redis +// Definitions by: Nick Simmons +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {ClientOpts} from 'redis'; +import {SessionStore} from 'koa-generic-session'; + +declare namespace redisStore { + interface RedisOptions extends ClientOpts { + duplicate?: boolean; + client?: any; + } +} + +declare function redisStore(options: redisStore.RedisOptions): SessionStore; +export = redisStore; diff --git a/types/koa-redis/koa-redis-tests.ts b/types/koa-redis/koa-redis-tests.ts new file mode 100644 index 0000000000..68d557336c --- /dev/null +++ b/types/koa-redis/koa-redis-tests.ts @@ -0,0 +1,20 @@ +import * as Koa from "koa"; +import {MemoryStore, Session} from "koa-generic-session"; +import session = require("koa-generic-session"); +import redisStore = require("koa-redis"); + +const app = new Koa(); + +app.use(session({ + store: redisStore({ + url: 'redis://url:123', + host: 'redisHost', + port: 123, + path: 'redis/path', + db: '2', + duplicate: false, + client: {} + }) +})); + +app.listen(80); diff --git a/types/koa-redis/tsconfig.json b/types/koa-redis/tsconfig.json new file mode 100644 index 0000000000..c6a27579dd --- /dev/null +++ b/types/koa-redis/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-redis-tests.ts" + ] +} diff --git a/types/koa-redis/tslint.json b/types/koa-redis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-redis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-route/index.d.ts b/types/koa-route/index.d.ts new file mode 100644 index 0000000000..4ee63b7b14 --- /dev/null +++ b/types/koa-route/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for koa-route 3.2 +// Project: https://github.com/koajs/route#readme +// Definitions by: Mike Cook +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Koa from 'koa'; +import * as pathToRegexp from 'path-to-regexp'; + +type RoutePath = string | RegExp | Array; + +type RouteHandler = (this: Koa.Context, ctx: Koa.Context, ...params: any[]) => any; + +type CreateRoute = (routeFunc: RouteHandler) => Koa.Middleware; + +interface RouteMethod { + (path: RoutePath): CreateRoute; + (path: RoutePath, fn: RouteHandler, opts?: pathToRegexp.ParseOptions & pathToRegexp.RegExpOptions): Koa.Middleware; +} + +type CreateRouteMethod = (method: string) => RouteMethod; + +interface KoaRoutes { + all: CreateRouteMethod; + acl: RouteMethod; + bind: RouteMethod; + checkout: RouteMethod; + connect: RouteMethod; + copy: RouteMethod; + delete: RouteMethod; + del: RouteMethod; + get: RouteMethod; + head: RouteMethod; + link: RouteMethod; + lock: RouteMethod; + msearch: RouteMethod; + merge: RouteMethod; + mkactivity: RouteMethod; + mkcalendar: RouteMethod; + mkcol: RouteMethod; + move: RouteMethod; + notify: RouteMethod; + options: RouteMethod; + patch: RouteMethod; + post: RouteMethod; + propfind: RouteMethod; + proppatch: RouteMethod; + purge: RouteMethod; + put: RouteMethod; + rebind: RouteMethod; + report: RouteMethod; + search: RouteMethod; + subscribe: RouteMethod; + trace: RouteMethod; + unbind: RouteMethod; + unlink: RouteMethod; + unlock: RouteMethod; + unsubscribe: RouteMethod; +} + +declare const routes: KoaRoutes; + +export = routes; diff --git a/types/koa-route/koa-route-tests.ts b/types/koa-route/koa-route-tests.ts new file mode 100644 index 0000000000..331c7d6b53 --- /dev/null +++ b/types/koa-route/koa-route-tests.ts @@ -0,0 +1,21 @@ +import * as Koa from 'koa'; +import * as route from 'koa-route'; + +const app = new Koa(); + +const getData = async (param: string) => Promise.resolve({ foo: param }); + +const getter = route.get('/'); +const getterMiddleware = getter((ctx, next) => { + ctx.body = { status: 'OK' }; + next(); +}); + +const putter = route.put('/api/:param', async (ctx, param, next) => { + const data = await getData(param); + ctx.body = { status: 'OK', ...data }; + next(); +}); + +app.use(getterMiddleware); +app.use(putter); diff --git a/types/koa-route/package.json b/types/koa-route/package.json new file mode 100644 index 0000000000..1bac4155dc --- /dev/null +++ b/types/koa-route/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "path-to-regexp": "^1.7.0" + } +} diff --git a/types/koa-route/tsconfig.json b/types/koa-route/tsconfig.json new file mode 100644 index 0000000000..7b54228aaa --- /dev/null +++ b/types/koa-route/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-route-tests.ts" + ] +} diff --git a/types/koa-route/tslint.json b/types/koa-route/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-route/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts new file mode 100644 index 0000000000..115dbb43f6 --- /dev/null +++ b/types/koa-websocket/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for koa-websocket 2.1 +// Project: https://github.com/kudos/koa-websocket +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Koa from 'koa'; +import * as ws from 'ws'; +import * as http from 'http'; +import * as https from 'https'; + +type KoaWebsocketConnectionHandler = (socket: ws) => void; +type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise) => any; +interface KoaWebsocketMiddlewareContext extends Koa.Context { + websocket: ws; + path: string; +} + +declare class KoaWebsocketServer { + app: Koa; + middleware: Koa.Middleware[]; + + constructor(app: Koa); + listen(server: http.Server | https.Server): ws.Server; + onConnection(handler: KoaWebsocketConnectionHandler): void; + use(middleware: KoaWebsocketMiddleware): this; +} + +interface KoaWebsocketApp extends Koa { + ws: KoaWebsocketServer; +} + +type KoaWebsockets = (app: Koa) => KoaWebsocketApp; + +declare const websockets: KoaWebsockets; +export = websockets; diff --git a/types/koa-websocket/koa-websocket-tests.ts b/types/koa-websocket/koa-websocket-tests.ts new file mode 100644 index 0000000000..66bd4bf4d2 --- /dev/null +++ b/types/koa-websocket/koa-websocket-tests.ts @@ -0,0 +1,14 @@ +import * as Koa from 'koa'; +import * as websocket from 'koa-websocket'; + +const app = websocket(new Koa()); + +app.ws.use(async function(context, next) { + this.websocket.on('message', (message) => { + console.log(message); + }); + this.websocket.send('Hello world'); + await next(); +}); + +app.listen(3000); diff --git a/types/koa-websocket/tsconfig.json b/types/koa-websocket/tsconfig.json new file mode 100644 index 0000000000..effcb59356 --- /dev/null +++ b/types/koa-websocket/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-websocket-tests.ts" + ] +} diff --git a/types/koa-websocket/tslint.json b/types/koa-websocket/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-websocket/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/launchpad/index.d.ts b/types/launchpad/index.d.ts index c39db51f2e..158485f818 100644 --- a/types/launchpad/index.d.ts +++ b/types/launchpad/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for launchpad +// Type definitions for launchpad 0.6.0 // Project: https://www.npmjs.com/package/launchpad // Definitions by: Peter Burns // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -34,16 +34,6 @@ export function browserstack( authCreds: BrowserstackAuth, cb: (err: any, browserstack: Launcher) => void): void; -interface RemoteConnectionOptions { - host: string; - username: string; - password: string; -} - -export function remote( - connectionOpts: RemoteConnectionOptions, - cb: (err: any, remoteLauncher: Launcher) => void): void; - interface BrowserPlatformDetails { pathQuery?: string; plistPath?: string; diff --git a/types/launchpad/launchpad-tests.ts b/types/launchpad/launchpad-tests.ts index e73beb47e5..0aa9d81104 100644 --- a/types/launchpad/launchpad-tests.ts +++ b/types/launchpad/launchpad-tests.ts @@ -43,19 +43,3 @@ launch.browserstack({ }, 5000); }); }); - -launch.remote({ - host : "ie7machine", - username : "launcher", - password : "testing" -}, function(err, api) { - api.browsers(function(error, browsers) { - // -> List of all browsers found on ie7machine - }); - - api("http://github.com", { - browser : "safari", - version : "latest" - }, function(err, instance) { - }); -}); diff --git a/types/leaflet-areaselect/index.d.ts b/types/leaflet-areaselect/index.d.ts new file mode 100644 index 0000000000..d4d93b6303 --- /dev/null +++ b/types/leaflet-areaselect/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for Leaflet.areaSelect 0.1 +// Project: https://github.com/heyman/leaflet-areaselect +// Definitions by: André Wallat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + function areaSelect(box: AreaSelectOptions): AreaSelect; + + interface AreaSelectOptions { + width?: number; + height?: number; + keepAspectRatio?: boolean; + } + + interface Dimension { + width: number; + height: number; + } + + interface AreaSelect { + addTo(map: Map): L.Map; + getBounds(): LatLngBounds; + remove(): void; + setDimensions(dim: Dimension): void; + } +} diff --git a/types/leaflet-areaselect/leaflet-areaselect-tests.ts b/types/leaflet-areaselect/leaflet-areaselect-tests.ts new file mode 100644 index 0000000000..b5d4785257 --- /dev/null +++ b/types/leaflet-areaselect/leaflet-areaselect-tests.ts @@ -0,0 +1,12 @@ +const map = L.map('map', {center: L.latLng(-37.7772, 175.2756), zoom: 15 }); +let area: L.AreaSelect; +let dim: L.Dimension = { width: 1, height: 2 }; + +area = L.areaSelect({}); + +area.remove(); +area.addTo(map); +area.getBounds(); +area.setDimensions(dim); + +L.areaSelect({width: 10, height: 30, keepAspectRatio: true}).addTo(map); diff --git a/types/promise/tsconfig.json b/types/leaflet-areaselect/tsconfig.json similarity index 84% rename from types/promise/tsconfig.json rename to types/leaflet-areaselect/tsconfig.json index 5fc066d3e9..efa50ab66e 100644 --- a/types/promise/tsconfig.json +++ b/types/leaflet-areaselect/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -17,6 +18,6 @@ }, "files": [ "index.d.ts", - "promise-tests.ts" + "leaflet-areaselect-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/leaflet-areaselect/tslint.json b/types/leaflet-areaselect/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/leaflet-areaselect/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/leaflet.awesome-markers/index.d.ts b/types/leaflet.awesome-markers/index.d.ts index ee6b65eaa4..48c58b8f60 100644 --- a/types/leaflet.awesome-markers/index.d.ts +++ b/types/leaflet.awesome-markers/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for Leaflet.awesome-markers plugin v2.0 -// Project: https://github.com/lvoogdt/Leaflet.awesome-markers +// Project: https://github.com/sigma-geosistemas/Leaflet.awesome-markers#properties // Definitions by: Egor Komarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -45,7 +45,7 @@ declare global { namespace L { /** * Color of the marker */ - markerColor?: 'red' | 'darkred' | 'orange' | 'green' | 'darkgreen' | 'blue' | 'purple' | 'darkpuple' | 'cadetblue'; + markerColor?: 'red' | 'darkred' | 'orange' | 'green' | 'darkgreen' | 'blue' | 'purple' | 'darkpurple' | 'cadetblue'; /** * Color of the icon. 'white', 'black' or css code (hex, rgba etc). diff --git a/types/leaflet.fullscreen/index.d.ts b/types/leaflet.fullscreen/index.d.ts index 67af1d6770..e38890b2d8 100644 --- a/types/leaflet.fullscreen/index.d.ts +++ b/types/leaflet.fullscreen/index.d.ts @@ -9,24 +9,27 @@ declare namespace L { namespace Control { - export interface Fullscreen extends L.Control {} - + export class Fullscreen extends L.Control { + constructor(options?: Control.FullscreenOptions); + options: FullscreenOptions; + } export interface FullscreenOptions { content?: string, - position?: string, - title?: string, - titleCancel?: string, - forceSeparateButton?: boolean, - forcePseudoFullscreen?: boolean + position?: L.ControlPosition, + title?: string, + titleCancel?: string, + forceSeparateButton?: boolean, + forcePseudoFullscreen?: boolean, + pseudoFullscreen?:boolean } } namespace control { - /** - * Creates a fullscreen control. - */ - export function fullscreen(options?: Control.FullscreenOptions): L.Control.Fullscreen; + /** + * Creates a fullscreen control. + */ + export function fullscreen(options?: Control.FullscreenOptions): L.Control.Fullscreen; } } diff --git a/types/leaflet-markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts similarity index 96% rename from types/leaflet-markercluster/index.d.ts rename to types/leaflet.markercluster/index.d.ts index f2323f4573..b6780ec357 100644 --- a/types/leaflet-markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -3,10 +3,12 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as Leaflet from "leaflet"; -declare namespace L { - interface MarkerCluster extends L.Marker { +export = Leaflet; + +declare global { namespace L { + interface MarkerCluster extends Marker { /* * Recursively retrieve all child markers of this cluster. */ @@ -103,7 +105,7 @@ declare namespace L { /* * Function used to create the cluster icon */ - iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon | L.DivIcon); + iconCreateFunction?: ((cluster: MarkerCluster) => Icon | DivIcon); /* * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. @@ -164,4 +166,4 @@ declare namespace L { * Create a marker cluster group, optionally given marker cluster group options. */ function markerClusterGroup(options?: MarkerClusterGroupOptions): MarkerClusterGroup; -} +} } diff --git a/types/leaflet-markercluster/leaflet-markercluster-tests.ts b/types/leaflet.markercluster/leaflet.markercluster-tests.ts similarity index 98% rename from types/leaflet-markercluster/leaflet-markercluster-tests.ts rename to types/leaflet.markercluster/leaflet.markercluster-tests.ts index 73b98586e9..2a2a4969e1 100644 --- a/types/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/types/leaflet.markercluster/leaflet.markercluster-tests.ts @@ -1,3 +1,5 @@ +import L = require("leaflet.markercluster"); + const polylineOptions: L.PolylineOptions = {}; const icon: L.Icon = L.icon({ iconUrl: 'foo' }); diff --git a/types/leaflet-markercluster/tsconfig.json b/types/leaflet.markercluster/tsconfig.json similarity index 91% rename from types/leaflet-markercluster/tsconfig.json rename to types/leaflet.markercluster/tsconfig.json index d5e7d33df8..6cc587aa00 100644 --- a/types/leaflet-markercluster/tsconfig.json +++ b/types/leaflet.markercluster/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "leaflet-markercluster-tests.ts" + "leaflet.markercluster-tests.ts" ] } \ No newline at end of file diff --git a/types/leaflet.markercluster/tslint.json b/types/leaflet.markercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leaflet.markercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lestate/index.d.ts b/types/lestate/index.d.ts index c606b93c36..ca9f6aab47 100644 --- a/types/lestate/index.d.ts +++ b/types/lestate/index.d.ts @@ -1,25 +1,21 @@ -// Type definitions for LeState v0.1.3 +// Type definitions for LeState 0.1 // Project: https://github.com/LeTools/LeState // Definitions by: Hadrian Oliveira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare let LeState : { - createState: (props?: { - initialState: {}; - }) => { - set(newValue: {}): [{ - id: number; - state: {}; - }]; - get(): any; - insert(newValue: {}): void; - getDescription(): {}; - createListener({ id, selector, force }: { - id: number; - selector: (state :any) => {}; - force?: boolean; - }): void; - }; -}; +export interface LeState { + set(newValue: {}): [{ + id: number; + state: {}; + }]; + get(): any; + insert(newValue: {}): void; + getDescription(): {}; + createListener(options: { + id: number; + selector(state: any): {}; + force?: boolean; + }): void; +} -export = LeState; +export function createState(props?: { initialState: {} }): LeState; diff --git a/types/lestate/lestate-tests.ts b/types/lestate/lestate-tests.ts index 3c2b074d2d..6eb3ad6d96 100644 --- a/types/lestate/lestate-tests.ts +++ b/types/lestate/lestate-tests.ts @@ -1,19 +1,19 @@ import LeState = require("lestate"); -let State = LeState.createState() +let State = LeState.createState(); State.set({ test : {} -}) +}); -let currentState = State.get() +let currentState = State.get(); State.insert({ test : {} -}) +}); -let currentDescription = State.getDescription() +let currentDescription = State.getDescription(); State.createListener({ id : 0, selector : state => ({ test : state.test }) -}) +}); diff --git a/types/lestate/tslint.json b/types/lestate/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/lestate/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/level-sublevel/index.d.ts b/types/level-sublevel/index.d.ts index f6a8f30943..9db592ec0f 100644 --- a/types/level-sublevel/index.d.ts +++ b/types/level-sublevel/index.d.ts @@ -3,22 +3,25 @@ // Definitions by: Bas Pennings // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as levelup from "levelup"; +export = sublevel + +declare var sublevel: sublevel.Constructor; + +declare namespace sublevel { interface Hook { (ch: any, add: (op: Batch|boolean) => void): void; } -interface Batch { +interface Batch extends levelup.Batch { prefix?: Sublevel; } -interface Sublevel extends LevelUp { +interface Sublevel extends levelup.LevelUpBase { sublevel(key: string): Sublevel; pre(hook: Hook): Function; } -declare module "level-sublevel" { - function sublevel(levelup: LevelUp): Sublevel; - export = sublevel; -} \ No newline at end of file +type Constructor = (levelup: levelup.LevelUp) => Sublevel +} diff --git a/types/leveldown/index.d.ts b/types/leveldown/index.d.ts new file mode 100644 index 0000000000..51630dc602 --- /dev/null +++ b/types/leveldown/index.d.ts @@ -0,0 +1,145 @@ +// Type definitions for LevelDown 1.7 +// Project: https://github.com/level/leveldown +// Definitions by: Thiago de Arruda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = leveldown; + +declare var leveldown: leveldown.Constructor; + +declare namespace leveldown { +type Bytes = string | Buffer; +type ErrCallback = (error: any) => void; +type ErrNumberCallback = (error: any, value: number) => void; +type ErrBufferCallback = (error: any, value: Buffer) => void; +type ErrStringCallback = (error: any, value: string) => void; +type KeyAsStringCallback = (error: any, key: string, value: Buffer) => void; +type ValueAsStringCallback = (error: any, key: Buffer, value: string) => void; +type KeyAndValueAsStringCallback = (error: any, key: string, value: string) => void; +type KeyAndValueAsBufferCallback = (error: any, key: Buffer, value: Buffer) => void; + +interface PutBatch { + type: "put"; + key: Bytes; + value: Bytes; +} + +interface DelBatch { + type: "del"; + key: Bytes; +} + +type Batch = PutBatch | DelBatch; + +interface OpenOptions { + createIfMissing?: boolean; + errorIfExists?: boolean; + compression?: boolean; + cacheSize?: number; +} + +interface OpenAdvancedOptions extends OpenOptions { + writeBufferSize?: number; + blockSize?: number; + maxOpenFiles?: number; + blockRestartInterval?: number; + maxFileSize?: number; +} + +interface WriteOptions { + sync?: boolean; +} + +interface ReadOptions { + fillCache?: boolean; +} + +interface BufferReadOptions extends ReadOptions { + asBuffer?: true; +} + +interface StringReadOptions extends ReadOptions { + asBuffer: false; +} + +interface IteratorOptions { + gt?: Bytes; + lt?: Bytes; + gte?: Bytes; + lte?: Bytes; + reverse?: boolean; + keys?: boolean; + values?: boolean; + limit?: number; + fillCache?: boolean; +} + +interface KeyAsStringIteratorOptions extends IteratorOptions { + keyAsBuffer: false; + valueAsBuffer?: true; +} + +interface ValueAsStringIteratorOptions extends IteratorOptions { + keyAsBuffer?: true; + valueAsBuffer: false; +} + +interface KeyAndValueAsStringIteratorOptions extends IteratorOptions { + keyAsBuffer: false; + valueAsBuffer: false; +} + +interface KeyAndValueAsBufferIteratorOptions extends IteratorOptions { + keyAsBuffer?: true; + valueAsBuffer?: true; +} + +interface Iterator { + seek(key: Bytes): void; + end(callback: ErrCallback): void; +} + +interface KeyAsStringIterator extends Iterator { + next(callback: KeyAsStringCallback): void; +} + +interface ValueAsStringIterator extends Iterator { + next(callback: ValueAsStringCallback): void; +} + +interface KeyAndValueAsStringIterator extends Iterator { + next(callback: KeyAndValueAsStringCallback): void; +} + +interface KeyAndValueAsBufferIterator extends Iterator { + next(callback: KeyAndValueAsBufferCallback): void; +} + +interface LevelDown { + open(callback: ErrCallback): void; + open(options: OpenOptions, callback: ErrCallback): void; + close(callback?: ErrCallback): void; + put(key: Bytes, value: Bytes, callback: ErrCallback): void; + put(key: Bytes, value: Bytes, options: WriteOptions, callback: ErrCallback): void; + get(key: Bytes, callback: ErrBufferCallback): void; + get(key: Bytes, options: BufferReadOptions, callback: ErrBufferCallback): void; + get(key: Bytes, options: StringReadOptions, callback: ErrStringCallback): void; + del(key: Bytes, callback?: ErrCallback): void; + del(key: Bytes, options: WriteOptions, callback?: ErrCallback): void; + batch(operations: Batch[], callback?: ErrCallback): void; + batch(operations: Batch[], options?: WriteOptions, callback?: ErrCallback): void; + approximateSize(start: Bytes, end: Bytes, callback: ErrNumberCallback): void; + compactRange(start: Bytes, end: Bytes, callback: ErrCallback): void; + getProperty(property: string): string; + iterator(options?: KeyAsStringIteratorOptions): KeyAsStringIterator; + iterator(options?: ValueAsStringIteratorOptions): ValueAsStringIterator; + iterator(options?: KeyAndValueAsStringIteratorOptions): KeyAndValueAsStringIterator; + iterator(options?: KeyAndValueAsBufferIteratorOptions): KeyAndValueAsBufferIterator; + destroy(location: string, callback: ErrCallback): void; + repair(location: string, callback: ErrCallback): void; +} + +type Constructor = (location: string) => LevelDown; +} diff --git a/types/leveldown/leveldown-tests.ts b/types/leveldown/leveldown-tests.ts new file mode 100644 index 0000000000..f627f422f5 --- /dev/null +++ b/types/leveldown/leveldown-tests.ts @@ -0,0 +1,86 @@ +import * as leveldown from "leveldown"; + +let db = leveldown("db1"); + +db.open((err) => {}); +db.open({createIfMissing: true}, (err) => {}); + +db.put("key", "value", (err) => {}); +db.put(Buffer.from("key"), Buffer.from("value"), (err) => {}); +db.put("key", "value", {sync: true}, (err) => {}); + +db.get("key", {asBuffer: false}, (error, val) => { + console.log(val.toUpperCase()); +}); +db.get("key", {fillCache: true}, (error, val) => { + console.log(val.readUInt32BE(0)); +}); +db.get("key", (error, val) => { + console.log(val.readUInt32BE(0)); +}); + +db.del("key"); +db.del("key", (error) => {}); +db.del("key", {sync: true}, (error) => {}); + +db.batch([{ + type: "put", key: "k", value: "v" +}, { + type: "del", key: "k" +}], (error) => {}); + +const keyAsStringIterator = db.iterator({keyAsBuffer: false}); +keyAsStringIterator.next((err, k, v) => { + console.log(k.toUpperCase()); + console.log(v.readUInt32BE(0)); +}); + +const valueAsStringIterator = db.iterator({valueAsBuffer: false}); +valueAsStringIterator.next((err, k, v) => { + console.log(k.readUInt32BE(0)); + console.log(v.toUpperCase()); +}); + +const keyAndValueAsStringIterator = db.iterator({keyAsBuffer: false, valueAsBuffer: false}); +keyAndValueAsStringIterator.next((err, k, v) => { + console.log(k.toUpperCase()); + console.log(v.toUpperCase()); +}); + +const keyAndValueAsBufferIterator1 = db.iterator({keyAsBuffer: true, valueAsBuffer: true}); +keyAndValueAsBufferIterator1.next((err, k, v) => { + console.log(k.readUInt32BE(0)); + console.log(v.readUInt32BE(0)); +}); + +const keyAndValueAsBufferIterator2 = db.iterator({keyAsBuffer: true}); +keyAndValueAsBufferIterator2.next((err, k, v) => { + console.log(k.readUInt32BE(0)); + console.log(v.readUInt32BE(0)); +}); + +const keyAndValueAsBufferIterator3 = db.iterator({valueAsBuffer: true}); +keyAndValueAsBufferIterator3.next((err, k, v) => { + console.log(k.readUInt32BE(0)); + console.log(v.readUInt32BE(0)); +}); + +const keyAndValueAsBufferIterator4 = db.iterator({}); +keyAndValueAsBufferIterator4.next((err, k, v) => { + console.log(k.readUInt32BE(0)); + console.log(v.readUInt32BE(0)); +}); + +keyAndValueAsBufferIterator4.seek("k"); +keyAndValueAsBufferIterator4.end((err) => {}); + +let s: string = db.getProperty("leveldb.stats"); + +db.approximateSize("k1", "k2", (err, size) => { + console.log(size.toExponential()); +}); + +db.compactRange("k1", "k2", (err) => {}); + +db.destroy("/path/to/db", (err) => {}); +db.repair("/path/to/db", (err) => {}); diff --git a/types/leveldown/tsconfig.json b/types/leveldown/tsconfig.json new file mode 100644 index 0000000000..c69d58061a --- /dev/null +++ b/types/leveldown/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leveldown-tests.ts" + ] +} diff --git a/types/leveldown/tslint.json b/types/leveldown/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leveldown/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/levelup/index.d.ts b/types/levelup/index.d.ts index b78d2e6e5a..69c816638b 100644 --- a/types/levelup/index.d.ts +++ b/types/levelup/index.d.ts @@ -5,6 +5,14 @@ /// +import * as leveldown from "leveldown"; + +export = levelup; + +declare var levelup: levelup.LevelUpConstructor; + +declare namespace levelup { + interface CustomEncoding { encode(val: any): Buffer| string; decode(val: Buffer | string): any; @@ -21,7 +29,8 @@ interface Batch { keyEncoding?: Encoding; valueEncoding?: Encoding; } -interface LevelUp { + +interface LevelUpBase { open(callback ?: (error : any) => any): void; close(callback ?: (error : any) => any): void; put(key: any, value: any, callback ?: (error: any) => any): void; @@ -33,8 +42,8 @@ interface LevelUp { del(key: any, options ?: { keyEncoding?: Encoding; sync?: boolean }, callback ?: (error: any) => any): void; - batch(array: Batch[], options?: { keyEncoding?: Encoding; valueEncoding?: Encoding; sync?: boolean }, callback?: (error?: any)=>any): void; - batch(array: Batch[], callback?: (error?: any)=>any): void; + batch(array: BatchType[], options?: { keyEncoding?: Encoding; valueEncoding?: Encoding; sync?: boolean }, callback?: (error?: any)=>any): void; + batch(array: BatchType[], callback?: (error?: any)=>any): void; batch():LevelUpChain; isOpen():boolean; isClosed():boolean; @@ -46,6 +55,8 @@ interface LevelUp { repair(location: string, callback?: Function): void; } +type LevelUp = LevelUpBase + interface LevelUpChain { put(key: any, value: any): LevelUpChain; put(key: any, value: any, options?: { sync?: boolean }): LevelUpChain; @@ -62,18 +73,10 @@ interface levelupOptions { cacheSize?: number; keyEncoding?: Encoding; valueEncoding?: Encoding; - db?: string + db?: leveldown.Constructor; } -declare module "levelup" { - - function levelup(hostname: string, options?: levelupOptions): LevelUp; - - export = levelup; +interface LevelUpConstructor { + (hostname: string, options?: levelupOptions): LevelUp; } - -declare module "leveldown" { - - export function destroy(location: string, callback?: Function): void; - export function repair(location: string, callback?: Function): void; } diff --git a/types/levelup/levelup-tests.ts b/types/levelup/levelup-tests.ts index 57eea64e63..8827512437 100644 --- a/types/levelup/levelup-tests.ts +++ b/types/levelup/levelup-tests.ts @@ -1,4 +1,4 @@ -import levelup = require("levelup"); +import * as levelup from "levelup"; interface BufferEncoding { encode(val: any): Buffer; @@ -82,7 +82,3 @@ db.createReadStream() .on('end', function () { console.log('Stream closed') }) - -import leveldown = require('leveldown'); -leveldown.destroy('mypath', ()=>{}); -leveldown.repair('mypath', ()=>{}); diff --git a/types/lodash-decorators/index.d.ts b/types/lodash-decorators/index.d.ts index 26f755813c..1085db3a3a 100644 --- a/types/lodash-decorators/index.d.ts +++ b/types/lodash-decorators/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for lodash-decorators 1.0.5 +// Type definitions for lodash-decorators 3.0 // Project: https://github.com/steelsojka/lodash-decorators -// Definitions by: Qubo +// Definitions by: Alan Agius , Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -8,75 +8,56 @@ declare module "lodash-decorators" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } - export interface TypedMethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor { - } + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - export interface Accessor { + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor { } + + interface Accessor { set: T; get: T; proto: T; } - export interface DebounceDecorator { - (wait: number, options?: _.DebounceSettings): MethodDecorator; - } - export interface ThrottleDecorator { - (wait: number, options?: _.ThrottleSettings): MethodDecorator; - } - export interface MemoizeDecorator { - (resolver?: Function): MethodDecorator; - } - export interface AfterDecorator { - (n: number): MethodDecorator; - } - export interface BeforeDecorator { - (n: number): MethodDecorator; - } - export interface AryDecorator { - (n: number): MethodDecorator; - } - export interface CurryDecorator { - (arity?: number): MethodDecorator; - } - export interface CurryRightDecorator { - (arity?: number): MethodDecorator; - } - export interface RestParamDecorator { - (start?: number): MethodDecorator; - } - export interface PartialDecorator { - (func: Function|string, ...args: any[]): MethodDecorator; - } - export interface WrapDecorator { - (wrapper: ((func: Function, ...args: any[]) => any)|string): MethodDecorator; - } - export interface ComposeDecorator { - (...funcs: (Function|string)[]): MethodDecorator; - } - export interface DelayDecorator { - (wait: number, ...args: any[]): MethodDecorator; - } - export interface DeferDecorator { - (...args: any[]): MethodDecorator; - } - export interface BindDecorator { + type DebounceDecorator = (wait: number, options?: _.DebounceSettings) => MethodDecorator; + + type ThrottleDecorator = (wait: number, options?: _.ThrottleSettings) => MethodDecorator; + + type MemoizeDecorator = (resolver?: Function) => MethodDecorator; + + type AfterDecorator = (n: number) => MethodDecorator; + + type BeforeDecorator = (n: number) => MethodDecorator; + + type AryDecorator = (n: number) => MethodDecorator; + + type CurryDecorator = (arity?: number) => MethodDecorator; + + type CurryRightDecorator = (arity?: number) => MethodDecorator; + + type RestDecorator = (start?: number) => MethodDecorator; + + type OverArgsDecorator = (func: Function, ...transforms: Function[]) => MethodDecorator; + + type PartialDecorator = (func: Function | string, ...args: any[]) => MethodDecorator; + + type WrapDecorator = (wrapper: ((func: Function, ...args: any[]) => any) | string) => MethodDecorator; + + type ComposeDecorator = (...funcs: Array<(Function | string)>) => MethodDecorator; + + type DelayDecorator = (wait: number, ...args: any[]) => MethodDecorator; + + type DeferDecorator = (...args: any[]) => MethodDecorator; + + interface BindDecorator { (): TypedMethodDecorator<(() => R)>; (param1?: T1): TypedMethodDecorator<((param1: T1) => R)>; @@ -91,161 +72,144 @@ declare module "lodash-decorators" { (param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5, param6?: T6): TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; } - export interface BindAllDecorator { - (...methodNames: string[]): ClassDecorator; - } - export interface ModArgsDecorator { - (...transforms: Function[]): MethodDecorator; - } - export const debounce: DebounceDecorator & Accessor; - export const Debounce: DebounceDecorator & Accessor; + type BindAllDecorator = (...methodNames: string[]) => ClassDecorator; - export const throttle: ThrottleDecorator & Accessor; - export const Throttle: ThrottleDecorator & Accessor; + const debounce: DebounceDecorator & Accessor; + const Debounce: DebounceDecorator & Accessor; - export const memoize: MemoizeDecorator & Accessor; - export const Memoize: MemoizeDecorator & Accessor; + const throttle: ThrottleDecorator & Accessor; + const Throttle: ThrottleDecorator & Accessor; - export const after: AfterDecorator & Accessor; - export const After: AfterDecorator & Accessor; + const memoize: MemoizeDecorator & Accessor; + const Memoize: MemoizeDecorator & Accessor; - export const before: BeforeDecorator & Accessor; - export const Before: BeforeDecorator & Accessor; + const after: AfterDecorator & Accessor; + const After: AfterDecorator & Accessor; - export const ary: AryDecorator & Accessor; - export const Ary: AryDecorator & Accessor; + const before: BeforeDecorator & Accessor; + const Before: BeforeDecorator & Accessor; - export const curry: CurryDecorator & Accessor; - export const Curry: CurryDecorator & Accessor; + const ary: AryDecorator & Accessor; + const Ary: AryDecorator & Accessor; - export const curryRight: CurryRightDecorator & Accessor; - export const CurryRight: CurryRightDecorator & Accessor; + const curry: CurryDecorator & Accessor; + const Curry: CurryDecorator & Accessor; - export const restParam: RestParamDecorator & Accessor; - export const RestParam: RestParamDecorator & Accessor; + const curryRight: CurryRightDecorator & Accessor; + const CurryRight: CurryRightDecorator & Accessor; - export const partial: PartialDecorator & Accessor; - export const Partial: PartialDecorator & Accessor; + const overArgs: OverArgsDecorator & Accessor; + const OverArgs: OverArgsDecorator & Accessor; - export const partialRight: PartialDecorator & Accessor; - export const PartialRight: PartialDecorator & Accessor; + const rest: RestDecorator & Accessor; + const Rest: RestDecorator & Accessor; - export const wrap: WrapDecorator & Accessor; - export const Wrap: WrapDecorator & Accessor; + const partial: PartialDecorator & Accessor; + const Partial: PartialDecorator & Accessor; - export const compose: ComposeDecorator & Accessor; - export const Compose: ComposeDecorator & Accessor; + const partialRight: PartialDecorator & Accessor; + const PartialRight: PartialDecorator & Accessor; - export const flow: ComposeDecorator & Accessor; - export const Flow: ComposeDecorator & Accessor; + const wrap: WrapDecorator & Accessor; + const Wrap: WrapDecorator & Accessor; - export const flowRight: ComposeDecorator & Accessor; - export const FlowRight: ComposeDecorator & Accessor; + const flow: ComposeDecorator & Accessor; + const Flow: ComposeDecorator & Accessor; - export const backflow: ComposeDecorator & Accessor; - export const Backflow: ComposeDecorator & Accessor; + const flowRight: ComposeDecorator & Accessor; + const FlowRight: ComposeDecorator & Accessor; - export const delay: DelayDecorator & Accessor; - export const Delay: DelayDecorator & Accessor; + const delay: DelayDecorator & Accessor; + const Delay: DelayDecorator & Accessor; - export const defer: DeferDecorator & Accessor; - export const Defer: DeferDecorator & Accessor; + const defer: DeferDecorator & Accessor; + const Defer: DeferDecorator & Accessor; - export const bind: BindDecorator & Accessor; - export const Bind: BindDecorator & Accessor; + const bind: BindDecorator & Accessor; + const Bind: BindDecorator & Accessor; - export const bindAll: BindAllDecorator; - export const BindAll: BindAllDecorator; + const bindAll: BindAllDecorator; + const BindAll: BindAllDecorator; - export const modArgs: ModArgsDecorator & Accessor; - export const ModArgs: ModArgsDecorator & Accessor; + const once: MethodDecoratorWithAccessor; + const Once: MethodDecoratorWithAccessor; - export const once: MethodDecoratorWithAccessor; - export const Once: MethodDecoratorWithAccessor; + const attempt: MethodDecoratorWithAccessor; + const Attempt: MethodDecoratorWithAccessor; - export const spread: MethodDecoratorWithAccessor; - export const Spread: MethodDecoratorWithAccessor; + const spread: MethodDecoratorWithAccessor; + const Spread: MethodDecoratorWithAccessor; - export const rearg: MethodDecoratorWithAccessor; - export const Rearg: MethodDecoratorWithAccessor; + const rearg: MethodDecoratorWithAccessor; + const Rearg: MethodDecoratorWithAccessor; - export const negate: MethodDecoratorWithAccessor; - export const Negate: MethodDecoratorWithAccessor; + const negate: MethodDecoratorWithAccessor; + const Negate: MethodDecoratorWithAccessor; - export const tap: MethodDecoratorWithAccessor; - export const Tap: MethodDecoratorWithAccessor; + const tap: MethodDecoratorWithAccessor; + const Tap: MethodDecoratorWithAccessor; + + const flip: MethodDecoratorWithAccessor; + const Flip: MethodDecoratorWithAccessor; } declare module "lodash-decorators/extensions" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface DeprecatedDecorator extends MethodDecorator, ClassDecorator { + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; + + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + interface DeprecatedDecorator extends MethodDecorator, ClassDecorator { methodAction(fn: Function & { name: string }): void; } - export const deprecated: DeprecatedDecorator; - export const Deprecated: DeprecatedDecorator; + const deprecated: DeprecatedDecorator; + const Deprecated: DeprecatedDecorator; - export const writable: (writable?: boolean) => MethodDecorator; - export const Writable: (writable?: boolean) => MethodDecorator; + function writable(writable?: boolean): MethodDecorator; + function Writable(writable?: boolean): MethodDecorator; - export const configurable: (configurable?: boolean) => MethodDecorator; - export const Configurable: (configurable?: boolean) => MethodDecorator; + function configurable(configurable?: boolean): MethodDecorator; + function Configurable(configurable?: boolean): MethodDecorator; - export const returnsArg: (index?: number) => MethodDecorator; - export const ReturnsArg: (index?: number) => MethodDecorator; + function returnsArg(index?: number): MethodDecorator; + function ReturnsArg(index?: number): MethodDecorator; - export const enumerable: (enumerable?: boolean) => MethodDecorator; - export const Enumerable: (enumerable?: boolean) => MethodDecorator; + function enumerable(enumerable?: boolean): MethodDecorator; + function Enumerable(enumerable?: boolean): MethodDecorator; - export const nonenumerable: MethodDecorator; - export const Nonenumerable: MethodDecorator; + const nonenumerable: MethodDecorator; + const Nonenumerable: MethodDecorator; - export const nonconfigurable: MethodDecorator; - export const Nonconfigurable: MethodDecorator; + const nonconfigurable: MethodDecorator; + const Nonconfigurable: MethodDecorator; - export const readonly: MethodDecorator; - export const Readonly: MethodDecorator; + const readonly: MethodDecorator; + const Readonly: MethodDecorator; } declare module "lodash-decorators/validate" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface TypedMethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - export interface Predicate { - (t: T): boolean; - } - type Predicates = Predicate|Predicate[]; + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - export interface ValidateDecorator { + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type Predicate = (t: T) => boolean; + + type Predicates = Predicate | Array>; + + interface ValidateDecorator { (p1: Predicates): TypedMethodDecorator<((param1: T1) => R)>; (p1: Predicates, p2?: Predicates): @@ -260,13 +224,11 @@ declare module "lodash-decorators/validate" { TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; } - export interface ValidateReturnDecorator { - (p1: Predicates): TypedMethodDecorator<((...args: any[]) => R)>; - } + type ValidateReturnDecorator = (p1: Predicates) => TypedMethodDecorator<((...args: any[]) => R)>; - export const validate: ValidateDecorator; - export const Validate: ValidateDecorator; + const validate: ValidateDecorator; + const Validate: ValidateDecorator; - export const validateReturn: ValidateReturnDecorator; - export const ValidateReturn: ValidateReturnDecorator; + const validateReturn: ValidateReturnDecorator; + const ValidateReturn: ValidateReturnDecorator; } diff --git a/types/lodash-decorators/lodash-decorators-tests.ts b/types/lodash-decorators/lodash-decorators-tests.ts index e22d6911f3..61c23f1ddb 100644 --- a/types/lodash-decorators/lodash-decorators-tests.ts +++ b/types/lodash-decorators/lodash-decorators-tests.ts @@ -2,7 +2,7 @@ // With Arguments // -import { after, debounce, memoize, curry } from 'lodash-decorators' +import { after, debounce, memoize, curry } from 'lodash-decorators'; class Person { firstName: string; @@ -15,7 +15,7 @@ class Person { @after(3) @debounce(100) getFullName(): string { - return `${this.firstName} ${this.lastName}` + return `${this.firstName} ${this.lastName}`; } @curry(2) @@ -28,7 +28,7 @@ class Person { // Without Arguments // -import { tap } from 'lodash-decorators' +import { tap } from 'lodash-decorators'; class Person2 { firstName: string; @@ -40,7 +40,7 @@ class Person2 { @once getFullName(): string { - return `${this.firstName} ${this.lastName}` + return `${this.firstName} ${this.lastName}`; } @tap @@ -51,13 +51,13 @@ class Person2 { const person2 = new Person2(); -person2.popIt([1, 2, 3]); //=> [1, 2] +person2.popIt([1, 2, 3]); // => [1, 2] // // Partials // -import { partial, wrap } from 'lodash-decorators' +import { partial, wrap } from 'lodash-decorators'; class Person3 { firstName: string; @@ -68,7 +68,7 @@ class Person3 { } getName(type: string) { - return type === 'firstName' ? this.firstName : this.lastName + return type === 'firstName' ? this.firstName : this.lastName; } @partial('getName', 'firstName') @@ -83,7 +83,7 @@ class Person3 { } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person3Ex extends Person3 { getUpperCaseName(): string; } @@ -97,8 +97,6 @@ person3.getUpperCaseName(); // JOE SMITH // // Composition // - -//import { kebabCase } from 'lodash'; import * as _ from 'lodash'; class Person4 { @@ -113,13 +111,13 @@ class Person4 { return `${this.firstName} ${this.lastName}`; } - @compose(_.kebabCase, 'getName') + @flow(_.kebabCase, 'getName') logName(name: string): void { console.log(name); } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person4Ex extends Person4 { logName(): void; } @@ -133,63 +131,62 @@ person4.logName(); // joe-smith // class Person5 { - @curry(2) // <= prototype decorator @debounce(100) // <= instance decorator - getName() {} //=> Throws an error. (╯°□°)╯︵ ┻━┻ + getName() { } // => Throws an error. (╯°□°)╯︵ ┻━┻ @debounce(100) // <= instance decorator @curry(2) // <= prototype decorator - getName2() {} //=> All is well :) + getName2() { } // => All is well :) } // // Getters and Setters // -import { once, compose } from 'lodash-decorators' +import { once, flow } from 'lodash-decorators'; -function alwaysArray(value: string|string[]): string[] { +function alwaysArray(value: string | string[]): string[] { return Array.isArray(value) ? value : _.isUndefined(value) ? [] : [value]; } class Person6 { - constructor() {} + constructor() { } private nameList: string[]; - //TODO: So far, TypeScript doesn't allow to put multiple decoratoes on set/get accessors. + // TODO: So far, TypeScript doesn't allow to put multiple decoratoes on set/get accessors. // see https://github.com/Microsoft/TypeScript/issues/2249#issuecomment-141684146 - //@once.get + // @once.get get names(): string[] { - //MEMO: Resolve type inconsistency + // MEMO: Resolve type inconsistency return [this.nameList.join(' ')]; - //MEMO: Original expression in repo - //return this.nameList.join(' '); + // MEMO: Original expression in repo + // return this.nameList.join(' '); } - @compose.set(alwaysArray) + @flow.set(alwaysArray) set names(names: string[]) { this.nameList = names; } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person6Alt { - names: string[]|string; + names: string[] | string; } const person6 = new Person6(); // nameList will always be an array. -person6.names = undefined; //=> [] -(person6 as Person6Alt).names = 'Joe'; //=> ['Joe'] -person6.names = ['Jim']; //=> ['Jim'] +person6.names = undefined; // => [] +(person6 as Person6Alt).names = 'Joe'; // => ['Joe'] +person6.names = ['Jim']; // => ['Jim'] // // Bind // -import { bind } from 'lodash-decorators' +import { bind } from 'lodash-decorators'; class Person7 { firstName: string; @@ -211,7 +208,7 @@ class Person7 { } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person7Ex extends Person7 { getUpperCaseName(): string; } @@ -221,8 +218,7 @@ const person7 = new Person7('Joe', 'Smith') as Person7Ex; person7.getName.call(null); // Joe Smith person7.getUpperCaseName(); // JOE - -import { bindAll } from 'lodash-decorators' +import { bindAll } from 'lodash-decorators'; @bindAll() class Person8 { @@ -250,16 +246,16 @@ import { throttle } from 'lodash-decorators'; class Person9 { @throttle(1000) - doStuff() {} + doStuff() { } @throttle.proto(1000) - doStuffMore() {} + doStuffMore() { } } const person9_1 = new Person9(); const person9_2 = new Person9(); -person9_1.doStuff(); //=> Both are called +person9_1.doStuff(); // => Both are called person9_2.doStuff(); person9_1.doStuffMore(); @@ -272,26 +268,25 @@ person9_2.doStuffMore(); // Extensions // -import { deprecated } from 'lodash-decorators/extensions' +import { deprecated } from 'lodash-decorators/extensions'; // This is applied globally. deprecated.methodAction = fn => console.log(`Don't use ${fn.name}!`); @deprecated class Person10 { - constructor() {} + constructor() { } } class OtherPerson { @deprecated - fn() {} + fn() { } } -let person10 = new Person10(); //=> Warning! - -let otherPerson = new OtherPerson(); -otherPerson.fn(); //=> Don't use fn! +const person10 = new Person10(); // => Warning! +const otherPerson = new OtherPerson(); +otherPerson.fn(); // => Don't use fn! // // https://github.com/steelsojka/lodash-decorators/tree/master/src/extensions @@ -300,10 +295,10 @@ otherPerson.fn(); //=> Don't use fn! import { Writable, ReturnsArg } from 'lodash-decorators/extensions'; class Person11 { - constructor() {} + constructor() { } @Writable(false) - getName() {} + getName() { } @ReturnsArg(1) doSomething(x: any, y: any, z: any) { @@ -319,7 +314,7 @@ import { Validate } from 'lodash-decorators/validate'; class Person12 { name: string; - constructor() {} + constructor() { } @Validate(_.isString) setName(name: any) { @@ -330,7 +325,7 @@ class Person12 { class Person13 { name: string; age: number; - constructor() {} + constructor() { } @Validate( _.isString, @@ -344,9 +339,8 @@ class Person13 { const person13 = new Person13(); -person13.setData('test', 5); //=> TypeError -person13.setData('test', 12); //=> Valid - +person13.setData('test', 5); // => TypeError +person13.setData('test', 12); // => Valid // // Additional typings diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 22b2d6b9e1..b8ae248190 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -18522,7 +18522,7 @@ declare namespace _ { * @param defaultValue The default value. * @returns Returns the resolved value. */ - defaultTo(value: T, defaultValue: T): T; + defaultTo(value: T | null | undefined, defaultValue: T): T; } interface LoDashImplicitWrapperBase { @@ -19591,20 +19591,20 @@ declare namespace _ { type ListIterator = (value: T, index: number, collection: List) => TResult; - type DictionaryIterator = (value: T, key?: string, collection?: Dictionary) => TResult; + type DictionaryIterator = (value: T, key: string, collection: Dictionary) => TResult; - type NumericDictionaryIterator = (value: T, key?: number, collection?: Dictionary) => TResult; + type NumericDictionaryIterator = (value: T, key: number, collection: Dictionary) => TResult; - type ObjectIterator = (element: T, key?: string, collection?: any) => TResult; + type ObjectIterator = (element: T, key: string, collection: any) => TResult; - type StringIterator = (char: string, index?: number, string?: string) => TResult; + type StringIterator = (char: string, index: number, string: string) => TResult; - type MemoVoidIterator = (prev: TResult, curr: T, indexOrKey?: any, list?: T[]) => void; + type MemoVoidIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void; - type MemoIterator = (prev: TResult, curr: T, indexOrKey?: any, list?: T[]) => TResult; + type MemoIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult; - type MemoVoidArrayIterator = (acc: TResult, curr: T, index?: number, arr?: T[]) => void; - type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key?: string, dict?: Dictionary) => void; + type MemoVoidArrayIterator = (acc: TResult, curr: T, index: number, arr: T[]) => void; + type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; // Common interface between Arrays and jQuery objects interface List { diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index af30a416d6..4f479eab83 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -96,7 +96,12 @@ interface TResult { } // _.MapCache -let testMapCache: _.MapCache; +let testMapCache: _.MapCache = { + delete(key: string) { return true; }, + get(key: string): any { return 1; }, + has(key: string) { return true; }, + set(key: string, value: any): _.Dictionary { return {}; }, +}; result = <(key: string) => boolean>testMapCache.delete; result = <(key: string) => any>testMapCache.get; result = <(key: string) => boolean>testMapCache.has; @@ -153,8 +158,8 @@ result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).unshift(5, // _.chunk namespace TestChunk { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[][]; @@ -189,8 +194,8 @@ namespace TestChunk { // _.compact namespace TestCompact { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -217,8 +222,8 @@ namespace TestCompact { // _.difference namespace TestDifference { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -265,9 +270,9 @@ namespace TestDifference { // _.differenceBy namespace TestDifferenceBy { - let array: TResult[]; - let list: _.List; - let iteratee: (value: TResult) => any; + let array: TResult[] = []; + let list: _.List = []; + let iteratee: (value: TResult) => any = (value: TResult) => 1; { let result: TResult[]; @@ -452,8 +457,8 @@ namespace TestDifferenceBy { // _.drop { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -487,8 +492,8 @@ namespace TestDifferenceBy { // _.dropRight namespace TestDropRight { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -523,9 +528,9 @@ namespace TestDropRight { // _.dropRightWhile namespace TestDropRightWhile { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index: number, collection: _.List) => boolean; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; { let result: TResult[]; @@ -572,9 +577,9 @@ namespace TestDropRightWhile { // _.dropWhile namespace TestDropWhile { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index: number, collection: _.List) => boolean; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; { let result: TResult[]; @@ -621,8 +626,8 @@ namespace TestDropWhile { // _.fill namespace TestFill { - let array: number[]; - let list: _.List; + let array: number[] = []; + let list: _.List = []; { let result: number[]; @@ -675,10 +680,10 @@ namespace TestFill { // _.findIndex namespace TestFindIndex { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; - let fromIndex: number; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; + let fromIndex: number = 0; { let result: number; @@ -727,11 +732,11 @@ namespace TestFindIndex { // _.findLastIndex namespace TestFindLastIndex { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; - let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; - let fromIndex: number; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; + let fromIndex: number = 0; { let result: number; @@ -780,8 +785,8 @@ namespace TestFindLastIndex { // _.first namespace TestFirst { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: string; @@ -992,8 +997,8 @@ namespace TestFlattenDeep { // _.fromPairs namespace TestFromPairs { - let twoDimensionalArray: string[][]; - let numberTupleArray: [string, number][]; + let twoDimensionalArray: string[][] = []; + let numberTupleArray: [string, number][] = []; let stringDict: _.Dictionary; let numberDict: _.Dictionary; @@ -1017,8 +1022,8 @@ namespace TestFromPairs { // _.head namespace TestHead { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: string; @@ -1053,9 +1058,9 @@ namespace TestHead { // _.indexOf namespace TestIndexOf { - let array: TResult[]; - let list: _.List; - let value: TResult; + let array: TResult[] = []; + let list: _.List = []; + let value: TResult = { a: 1, b: "", c: true }; { let result: number; @@ -1092,9 +1097,9 @@ namespace TestIndexOf { // _.sortedIndexOf namespace TestIndexOf { - let array: TResult[]; - let list: _.List; - let value: TResult; + let array: TResult[] = []; + let list: _.List = []; + let value: TResult = { a: 1, b: "", c: true }; { let result: number; @@ -1115,8 +1120,8 @@ namespace TestIndexOf { //_.initial namespace TestInitial { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1142,8 +1147,8 @@ namespace TestInitial { // _.intersection namespace TestIntersection { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1210,8 +1215,8 @@ namespace TestJoin { // _.last namespace TestLast { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: string; @@ -1251,9 +1256,9 @@ namespace TestLast { // _.lastIndexOf namespace TestLastIndexOf { - let array: TResult[]; - let list: _.List; - let value: TResult; + let array: TResult[] = []; + let list: _.List = []; + let value: TResult = { a: 1, b: "", c: true }; { let result: number; @@ -1290,9 +1295,9 @@ namespace TestLastIndexOf { // _.nth namespace TestNth { - let array: TResult[]; - let list: _.List; - let value: number; + let array: TResult[] = []; + let list: _.List = []; + let value: number = 0; { let result: TResult; @@ -1321,9 +1326,9 @@ namespace TestNth { // _.pull namespace TestPull { - let array: TResult[]; - let list: _.List; - let value: TResult; + let array: TResult[] = []; + let list: _.List = []; + let value: TResult = { a: 1, b: "", c: true }; { let result: TResult[]; @@ -1382,8 +1387,8 @@ namespace TestPull { // _.pullAt namespace TestPullAt { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1430,9 +1435,9 @@ namespace TestPullAt { // _.remove namespace TestRemove { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; { let result: TResult[]; @@ -1479,8 +1484,8 @@ namespace TestRemove { // _.tail namespace TestTail { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1506,7 +1511,7 @@ namespace TestTail { // _.slice namespace TestSlice { - let array: TResult[]; + let array: TResult[] = []; { let result: TResult[]; @@ -1537,10 +1542,10 @@ namespace TestSlice { namespace TestSortedIndex { type SampleType = {a: number; b: string; c: boolean;}; - let array: SampleType[]; - let list: _.List; + let array: SampleType[] = []; + let list: _.List = []; - let value: SampleType; + let value: SampleType = { a: 1, b: "", c: true }; let stringIterator: (x: string) => number; let arrayIterator: (x: SampleType) => number; @@ -1577,14 +1582,14 @@ namespace TestSortedIndex { namespace TestSortedIndexBy { type SampleType = {a: number; b: string; c: boolean;}; - let array: SampleType[]; - let list: _.List; + let array: SampleType[] = []; + let list: _.List = []; - let value: SampleType; + let value: SampleType = { a: 1, b: "", c: true }; - let stringIterator: (x: string) => number; - let arrayIterator: (x: SampleType) => number; - let listIterator: (x: SampleType) => number; + let stringIterator = (x: string) => 0; + let arrayIterator = (x: SampleType) => 0; + let listIterator = (x: SampleType) => 0; { let result: number; @@ -1638,10 +1643,10 @@ namespace TestSortedIndexBy { namespace TestSortedLastIndex { type SampleType = {a: number; b: string; c: boolean;}; - let array: SampleType[]; - let list: _.List; + let array: SampleType[] = []; + let list: _.List = []; - let value: SampleType; + let value: SampleType = { a: 1, b: "", c: true }; let stringIterator: (x: string) => number; let arrayIterator: (x: SampleType) => number; @@ -1678,14 +1683,14 @@ namespace TestSortedLastIndex { namespace TestSortedLastIndexBy { type SampleType = {a: number; b: string; c: boolean;}; - let array: SampleType[]; - let list: _.List; + let array: SampleType[] = []; + let list: _.List = []; - let value: SampleType; + let value: SampleType = { a: 1, b: "", c: true }; - let stringIterator: (x: string) => number; - let arrayIterator: (x: SampleType) => number; - let listIterator: (x: SampleType) => number; + let stringIterator = (x: string) => 0; + let arrayIterator = (x: SampleType) => 0; + let listIterator = (x: SampleType) => 0; { let result: number; @@ -1737,8 +1742,8 @@ namespace TestSortedLastIndexBy { // _.tail namespace TestTail { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1764,8 +1769,8 @@ namespace TestTail { // _.take namespace TestTake { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1800,8 +1805,8 @@ namespace TestTake { // _.takeRight namespace TestTakeRight { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1836,9 +1841,9 @@ namespace TestTakeRight { // _.takeRightWhile namespace TestTakeRightWhile { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index: number, collection: _.List) => boolean; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; { let result: TResult[]; @@ -1885,9 +1890,9 @@ namespace TestTakeRightWhile { // _.takeWhile namespace TestTakeWhile { - let array: TResult[]; - let list: _.List; - let predicateFn: (value: TResult, index: number, collection: _.List) => boolean; + let array: TResult[] = []; + let list: _.List = []; + let predicateFn = (value: TResult, index: number, collection: _.List) => true; { let result: TResult[]; @@ -1934,8 +1939,8 @@ namespace TestTakeWhile { // _.union namespace TestUnion { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -1986,9 +1991,9 @@ namespace TestUnion { // _.unionBy namespace TestUnionBy { - let array: TResult[]; - let list: _.List; - let iteratee: (value: TResult) => any; + let array: TResult[] = []; + let list: _.List = []; + let iteratee: (value: TResult) => any = (value: TResult) => 1; { let result: TResult[]; @@ -2151,11 +2156,8 @@ namespace TestUnionBy { namespace TestUniq { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[]; - let list: _.List; - - let stringIterator: (value: string, index: number, collection: string) => string; - let listIterator: (value: SampleObject, index: number, collection: _.List) => number; + let array: SampleObject[] = []; + let list: _.List = []; { let result: string[]; @@ -2199,11 +2201,11 @@ namespace TestUniq { namespace TestUniqBy { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[]; - let list: _.List; + let array: SampleObject[] = []; + let list: _.List = []; - let stringIterator: (value: string, index: number, collection: string) => string; - let listIterator: (value: SampleObject, index: number, collection: _.List) => number; + let stringIterator = (value: string, index: number, collection: string) => ""; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 0; { let result: string[]; @@ -2273,11 +2275,8 @@ namespace TestUniqBy { namespace TestSortedUniq { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[]; - let list: _.List; - - let stringIterator: (value: string, index: number, collection: string) => string; - let listIterator: (value: SampleObject, index: number, collection: _.List) => number; + let array: SampleObject[] = []; + let list: _.List = []; { let result: string[]; @@ -2317,11 +2316,11 @@ namespace TestSortedUniq { namespace TestSortedUniqBy { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[]; - let list: _.List; + let array: SampleObject[] = []; + let list: _.List = []; - let stringIterator: (value: string, index: number, collection: string) => string; - let listIterator: (value: SampleObject, index: number, collection: _.List) => number; + let stringIterator = (value: string, index: number, collection: string) => ""; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 0; { let result: string[]; @@ -2422,9 +2421,9 @@ namespace TestUnzip { // _.unzipWith { - let testUnzipWithArray: (number[]|_.List)[]; - let testUnzipWithList: _.List>; - let testUnzipWithIterator: {(prev: TResult, curr: number, index?: number, list?: number[]): TResult}; + let testUnzipWithArray: (number[]|_.List)[] = []; + let testUnzipWithList: _.List> = []; + let testUnzipWithIterator: {(prev: TResult, curr: number, index?: number, list?: number[]): TResult} = (prev: TResult, curr: number, index?: number, list?: number[]) => ({ a: 1, b: "", c: true }); let result: TResult[]; result = _.unzipWith(testUnzipWithArray); result = _.unzipWith(testUnzipWithArray, testUnzipWithIterator); @@ -2436,8 +2435,8 @@ namespace TestUnzip { // _.without namespace TestWithout { - let array: number[]; - let list: _.List; + let array: number[] = []; + let list: _.List = []; { let result: number[]; @@ -2483,8 +2482,8 @@ namespace TestWithout { // _.xor namespace TestXor { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[]; @@ -2527,8 +2526,8 @@ namespace TestXor { // _.zip namespace TestZip { - let array: TResult[]; - let list: _.List; + let array: TResult[] = []; + let list: _.List = []; { let result: TResult[][]; @@ -2565,13 +2564,13 @@ namespace TestZip { // _.zipObject namespace TestZipObject { - let arrayOfKeys: string[]; - let arrayOfValues: number[]; - let arrayOfKeyValuePairs: (string|number)[][] + let arrayOfKeys: string[] = []; + let arrayOfValues: number[] = []; + let arrayOfKeyValuePairs: (string|number)[][] = []; - let listOfKeys: _.List; - let listOfValues: _.List; - let listOfKeyValuePairs: _.List<_.List>; + let listOfKeys: _.List = []; + let listOfValues: _.List = []; + let listOfKeyValuePairs: _.List<_.List> = []; { let result: _.Dictionary; @@ -2717,7 +2716,7 @@ namespace TestZipObject { interface TestZipWithFn { (a1: number, a2: number): number; } -let testZipWithFn: TestZipWithFn; +let testZipWithFn: TestZipWithFn = (a1, a2) => 1; result = _.zipWith([1, 2]); result = _.zipWith([1, 2], testZipWithFn); result = _.zipWith([1, 2], [1, 2], testZipWithFn); @@ -2775,28 +2774,28 @@ namespace TestChain { // _.tap namespace TestTap { { - let interceptor: (value: string) => void; + let interceptor = (value: string) => {}; let result: string; _.tap('', interceptor); } { - let interceptor: (value: string[]) => void; + let interceptor = (value: string[]) => {}; let result: _.LoDashImplicitArrayWrapper; _.tap([''], interceptor); } { - let interceptor: (value: {a: string}) => void; + let interceptor = (value: {a: string}) => {}; let result: _.LoDashImplicitObjectWrapper<{a: string}>; _.tap({a: ''}, interceptor); } { - let interceptor: (value: string) => void; + let interceptor = (value: string) => {}; let result: _.LoDashImplicitWrapper; _.chain('').tap(interceptor); @@ -2805,7 +2804,7 @@ namespace TestTap { } { - let interceptor: (value: string[]) => void; + let interceptor = (value: string[]) => {}; let result: _.LoDashImplicitArrayWrapper; _.chain(['']).tap(interceptor); @@ -2814,7 +2813,7 @@ namespace TestTap { } { - let interceptor: (value: {a: string}) => void; + let interceptor = (value: {a: string}) => {}; let result: _.LoDashImplicitObjectWrapper<{a: string}>; _.chain({a: ''}).tap(interceptor); @@ -2823,7 +2822,7 @@ namespace TestTap { } { - let interceptor: (value: string) => void; + let interceptor = (value: string) => {}; let result: _.LoDashExplicitWrapper; _.chain('').tap(interceptor); @@ -2832,7 +2831,7 @@ namespace TestTap { } { - let interceptor: (value: string[]) => void; + let interceptor = (value: string[]) => {}; let result: _.LoDashExplicitArrayWrapper; _.chain(['']).tap(interceptor); @@ -2841,7 +2840,7 @@ namespace TestTap { } { - let interceptor: (value: {a: string}) => void; + let interceptor = (value: {a: string}) => {}; let result: _.LoDashExplicitObjectWrapper<{a: string}>; _.chain({a: ''}).tap(interceptor); @@ -2857,77 +2856,77 @@ namespace TestThru { } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: number; result = _.thru(1, interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashImplicitWrapper; result = _(1).thru(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashImplicitWrapper; result = _('').thru(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashImplicitWrapper; result = _(true).thru(interceptor); } { - let interceptor: Interceptor<{a: string}>; + let interceptor: Interceptor<{a: string}> = (x) => x; let result: _.LoDashImplicitObjectWrapper<{a: string}>; result = _({a: ''}).thru<{a: string}>(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashImplicitArrayWrapper; result = _([1, 2, 3]).thru(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashExplicitWrapper; result = _(1).chain().thru(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashExplicitWrapper; result = _('').chain().thru(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashExplicitWrapper; result = _(true).chain().thru(interceptor); } { - let interceptor: Interceptor<{a: string}>; + let interceptor: Interceptor<{a: string}> = (x) => x; let result: _.LoDashExplicitObjectWrapper<{a: string}>; result = _({a: ''}).chain().thru<{a: string}>(interceptor); } { - let interceptor: Interceptor; + let interceptor: Interceptor = (x) => x; let result: _.LoDashExplicitArrayWrapper; result = _([1, 2, 3]).chain().thru(interceptor); @@ -3255,9 +3254,9 @@ namespace TestValueOf { // _.at namespace TestAt { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; { let result: TResult[]; @@ -3286,15 +3285,15 @@ namespace TestAt { // _.countBy namespace TestCountBy { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; - let stringIterator: (value: string, index: number, collection: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; - let numericDictionaryIterator: (value: TResult, key: number, collection: _.NumericDictionary) => any; + let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let numericDictionaryIterator: (value: TResult, key: number, collection: _.NumericDictionary) => any = (value: TResult, key: number, collection: _.NumericDictionary) => 1; { let result: _.Dictionary; @@ -3392,13 +3391,13 @@ namespace TestCountBy { // _.each namespace TestEach { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string; @@ -3475,13 +3474,13 @@ namespace TestEach { // _.eachRight namespace TestEachRight { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string; @@ -3560,14 +3559,14 @@ namespace TestEachRight { namespace TestEvery { type SampleObject = {a: number; b: string; c: boolean;}; - let array: SampleObject[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: SampleObject[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; - let listIterator: (value: SampleObject, index: number, collection: _.List) => boolean; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => boolean; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => boolean; + let listIterator = (value: SampleObject, index: number, collection: _.List) => true; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => true; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => true; { let result: boolean; @@ -3652,13 +3651,13 @@ namespace TestEvery { // _.filter namespace TestFilter { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string[]; @@ -3738,14 +3737,14 @@ namespace TestFilter { // _.find namespace TestFind { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: TResult, index: number, collection: _.List) => boolean; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => boolean; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; - let result: TResult; + let result: TResult | undefined; result = _.find(array); result = _.find(array, listIterator); @@ -3822,13 +3821,13 @@ namespace TestFlatMap { let numNumericDictionary: _.NumericDictionary = {0: 1, 1: [2, 3]}; let objNumericDictionary: _.NumericDictionary<{a: number}|{a: number}[]> = {0: {a: 1}, 1: [{a: 2}, {a: 3}]}; - let stringIterator: (value: string, index: number, collection: _.List) => string|string[]; + let stringIterator: (value: string, index: number, collection: _.List) => string|string[] = (a, b, c) => ""; - let listIterator: (value: number, index: number, collection: _.List) => number|number[]; + let listIterator: (value: number, index: number, collection: _.List) => number|number[] = (a, b, c) => 1; - let dictionaryIterator: (value: number, key: number, collection: _.Dictionary) => number|number[]; + let dictionaryIterator: (value: number, key: number, collection: _.Dictionary) => number|number[] = (a, b, c) => 1; - let numericDictionaryIterator: (value: number, key: number, collection: _.NumericDictionary) => number|number[]; + let numericDictionaryIterator: (value: number, key: number, collection: _.NumericDictionary) => number|number[] = (a, b, c) => 1; { let result: string[]; @@ -4001,13 +4000,13 @@ namespace TestFlatMap { // _.forEach namespace TestForEach { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string; @@ -4084,13 +4083,13 @@ namespace TestForEach { // _.forEachRight namespace TestForEachRight { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string; @@ -4169,13 +4168,13 @@ namespace TestForEachRight { namespace TestGroupBy { type SampleType = {a: number; b: string; c: boolean;}; - let array: SampleType[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: SampleType[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => number; - let listIterator: (value: SampleType, index: number, collection: _.List) => number; - let dictionaryIterator: (value: SampleType, key: string, collection: _.Dictionary) => number; + let stringIterator = (char: string, index: number, string: string) => 0; + let listIterator = (value: SampleType, index: number, collection: _.List) => 0; + let dictionaryIterator = (value: SampleType, key: string, collection: _.Dictionary) => 0; { let result: _.Dictionary; @@ -4291,11 +4290,11 @@ namespace TestGroupBy { namespace TestIncludes { type SampleType = {a: string; b: number; c: boolean;}; - let array: SampleType[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: SampleType[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let target: SampleType; + let target: SampleType = { a: "", b: 1, c: true }; { let result: boolean; @@ -4337,15 +4336,15 @@ namespace TestIncludes { namespace TestKeyBy { type SampleObject = {a: number; b: string; c: boolean;}; - let array: SampleObject[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: SampleObject[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; - let stringIterator: (value: string, index: number, collection: string) => any; - let listIterator: (value: SampleObject, index: number, collection: _.List) => any; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any; + let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; + let listIterator: (value: SampleObject, index: number, collection: _.List) => any = (value: SampleObject, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any = (value: SampleObject, key: string, collection: _.Dictionary) => 1; + let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any = (value: SampleObject, key: number, collection: _.NumericDictionary) => 1; { let result: _.Dictionary; @@ -4583,12 +4582,12 @@ namespace TestInvokeMap { // _.map namespace TestMap { - let array: number[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: number[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: number, index: number, collection: _.List) => TResult; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => TResult; + let listIterator: (value: number, index: number, collection: _.List) => TResult = (value: number, index: number, collection: _.List) => ({ a: 1, b: "", c: true }); + let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => TResult = (value: number, key: string, collection: _.Dictionary) => ({ a: 1, b: "", c: true }); { _.map(array); // $ExpectType number[] @@ -4698,9 +4697,9 @@ result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a', // d: {b: TResult}[]; // } // -// let array: SampleObject[]; -// let list: _.List; -// let dictionary: _.Dictionary; +// let array: SampleObject[] = []; +// let list: _.List = []; +// let dictionary: _.Dictionary = {}; // // { // let result: any[]; @@ -4776,19 +4775,19 @@ namespace TestReduce { result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; - }, {}); + }, { a: 1, b: 2, c: 3 }); result = _.reduceRight([[0, 1], [2, 3], [4, 5]], (a: number[], b: number[]) => a.concat(b), []); } // _.reject namespace TestReject { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let stringIterator: (char: string, index: number, string: string) => any; - let listIterator: (value: TResult, index: number, collection: _.List) => any; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; + let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; { let result: string[]; @@ -4859,10 +4858,10 @@ namespace TestReject { // _.sample namespace TestSample { - let array: string[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: string[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; { let result: string; @@ -4897,10 +4896,10 @@ namespace TestSample { // _.sampleSize namespace TestSampleSize { - let array: string[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: string[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; { let result: string[]; @@ -4958,9 +4957,9 @@ namespace TestSampleSize { // _.shuffle namespace TestShuffle { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; { let result: string[]; @@ -5009,9 +5008,9 @@ namespace TestShuffle { namespace TestSize { type SampleType = {a: string; b: number; c: boolean;}; - let array: SampleType[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: SampleType[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; { let result: number; @@ -5041,16 +5040,16 @@ namespace TestSize { namespace TestSome { type SampleObject = {a: number; b: string; c: boolean;}; - let array: SampleObject[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; - let sampleObject: SampleObject; + let array: SampleObject[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; + let sampleObject: SampleObject = { a: 1, b: "", c: true }; - let listIterator: (value: SampleObject, index: number, collection: _.List) => boolean; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => boolean; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => boolean; - let objectIterator: (value: any, key: string, collection: any) => boolean; + let listIterator = (value: SampleObject, index: number, collection: _.List) => true; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => true; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => true; + let objectIterator = (value: any, key: string, collection: any) => true; { let result: boolean; @@ -5068,7 +5067,13 @@ namespace TestSome { result = _.some(list, {a: 42}); result = _.some(dictionary); - result = _.some(dictionary, dictionaryIterator); + result = _.some(numericDictionary, dictionaryIterator); + result = _.some(dictionary, (value, key, collection) => { + value.a--; + key.substr(0); + value = collection[key]; + return true; + }); result = _.some(dictionary, 'a'); result = _.some(dictionary, ['a', 42]); result = _.some(dictionary, {a: 42}); @@ -5153,12 +5158,12 @@ namespace TestSome { // _.sortBy namespace TestSortBy { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: TResult, index: number, collection: _.List) => number; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => number; + let listIterator = (value: TResult, index: number, collection: _.List) => 0; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => 0; { let result: TResult[]; @@ -5228,14 +5233,14 @@ result = _(foodsOrganic).sortBy('organic', (food) => food.name, namespace TestorderBy { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[]; - let list: _.List; - let numericDictionary: _.NumericDictionary; - let dictionary: _.Dictionary; - let orders: boolean|string|(boolean|string)[]; + let array: SampleObject[] = []; + let list: _.List = []; + let numericDictionary: _.NumericDictionary = {}; + let dictionary: _.Dictionary = {}; + let orders: boolean|string|(boolean|string)[] = true as any; { - let iteratees: (value: string) => any|((value: string) => any)[]; + let iteratees: (value: string) => any|((value: string) => any)[] = (value) => 1; let result: string[]; result = _.orderBy('acbd', iteratees); @@ -5243,7 +5248,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[]; + let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => 1; let result: SampleObject[]; result = _.orderBy<{a: number}, SampleObject>(array, iteratees); @@ -5268,7 +5273,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[]; + let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; let result: _.LoDashImplicitArrayWrapper; result = _(array).orderBy<{a: number}>(iteratees); @@ -5291,7 +5296,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[]; + let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; let result: _.LoDashExplicitArrayWrapper; result = _(array).chain().orderBy<{a: number}>(iteratees); @@ -5346,7 +5351,7 @@ namespace TestAfter { (a: string, b: number): boolean; } - let func: Func; + let func: Func = (a, b) => true; { let result: Func; @@ -5371,7 +5376,7 @@ namespace TestAfter { namespace TestAry { type SampleFunc = (a: number, b: string) => boolean; - let func: SampleFunc; + let func: SampleFunc = (a, b) => true; { let result: SampleFunc; @@ -5403,7 +5408,7 @@ namespace TestBefore { (a: string, b: number): boolean; } - let func: Func; + let func: Func = (a, b) => true; { let result: Func; @@ -5428,7 +5433,7 @@ namespace TestBefore { namespace TestBind { type SampleFunc = (a: number, b: string) => boolean; - let func: SampleFunc + let func: SampleFunc = (a, b) => true; { type SampleResult = (a: number, b: string) => boolean; @@ -5514,7 +5519,7 @@ namespace TestBindAll { c: Function; } - let object: SampleObject; + let object: SampleObject = { a: () => {}, b: () => {}, c: () => {} }; { let result: SampleObject; @@ -5546,9 +5551,9 @@ namespace TestBindAll { // _.bindKey namespace TestBindKey { - let object: { - foo(a: number, b: string): boolean; - } + let object = { + foo: (a: number, b: string) => true, + }; { type SampleResult = (a: number, b: string) => boolean; @@ -5699,8 +5704,8 @@ namespace TestDebounce { cancel(): void; } - let func: SampleFunc; - let options: Options; + let func: SampleFunc = (a, b) => true; + let options: Options = {}; { let result: ResultFunc; @@ -5731,7 +5736,7 @@ namespace TestDebounce { namespace TestDefer { type SampleFunc = (a: number, b: string) => boolean; - let func: SampleFunc; + let func: SampleFunc = (a, b) => true; { let result: number; @@ -5765,7 +5770,7 @@ namespace TestDefer { namespace TestDelay { type SampleFunc = (a: number, b: string) => boolean; - let func: SampleFunc; + let func: SampleFunc = (a, b) => true; { let result: number; @@ -5798,7 +5803,7 @@ namespace TestFlip { (a: number, b: string): boolean; } - let func: Func; + let func: Func = (a, b) => true; { let result: Func; @@ -5821,10 +5826,10 @@ namespace TestFlip { // _.flow namespace TestFlow { - let Fn1: (n: number) => number; - let Fn2: (m: number, n: number) => number; - let Fn3: (a: number) => string; - let Fn4: (a: string) => number; + let Fn1 = (n: number) => 0; + let Fn2 = (m: number, n: number) => 0; + let Fn3 = (a: number) => ""; + let Fn4 = (a: string) => 0; { // type infer test @@ -5866,8 +5871,8 @@ namespace TestFlow { // _.flowRight namespace TestFlowRight { - let Fn1: (n: number) => number; - let Fn2: (m: number, n: number) => number; + let Fn1 = (n: number) => 0; + let Fn2 = (m: number, n: number) => 0; { let result: (m: number, n: number) => number; @@ -5897,7 +5902,8 @@ namespace TestFlowRight { // _.memoize namespace TestMemoize { { - let memoizedFunction: _.MemoizedFunction; + let fn: any = () => {}; + let memoizedFunction: _.MemoizedFunction = fn; let cache: _.MapCache = memoizedFunction.cache; } @@ -5905,8 +5911,8 @@ namespace TestMemoize { (a1: string, a2: number): boolean; } - let memoizeFn: (a1: string, a2: number) => boolean; - let memoizeResolverFn: (a1: string, a2: number) => string; + let memoizeFn = (a1: string, a2: number) => true; + let memoizeResolverFn = (a1: string, a2: number) => ""; { let result: MemoizedResultFn; @@ -5938,12 +5944,14 @@ namespace TestMemoize { has(key: K): boolean; set(key: K, value: V): this; } - interface MemoizeCacheConstructor { - new (): MemoizeCache; + class MemoizeCacheClass implements MemoizeCache { + delete: (key: any) => true; + get: (key: any) => 1; + has: (key: any) => true; + set: (key: any, value: any) => this; } - let MemoizeCache: MemoizeCacheConstructor - _.memoize.Cache = MemoizeCache; + _.memoize.Cache = MemoizeCacheClass; } // _.overArgs @@ -5951,11 +5959,11 @@ namespace TestOverArgs { type Func1 = (a: boolean) => boolean; type Func2 = (a: boolean, b: boolean) => boolean; - let func1: Func1; - let func2: Func2; + let func1: Func1 = (a) => true; + let func2: Func2 = (a, b) => true; - let transform1: (a: string) => boolean; - let transform2: (b: number) => boolean; + let transform1 = (a: string) => true; + let transform2 = (b: number) => true; { let result: (a: string) => boolean; @@ -6040,7 +6048,7 @@ namespace TestOnce { (a: number, b: string): boolean; } - let func: Func; + let func: Func = (a, b) => true; { let result: Func; @@ -6089,7 +6097,7 @@ namespace TestRest { type Func = (a: string, b: number[]) => boolean; type ResultFunc = (a: string, ...b: number[]) => boolean; - let func: Func; + let func: Func = (a, b) => true; { let result: ResultFunc; @@ -6121,7 +6129,7 @@ namespace TestSpread { type SampleFunc = (args: (number|string)[]) => boolean; type SampleResult = (a: number, b: string) => boolean; - let func: SampleFunc; + let func: SampleFunc = (a) => true; { let result: SampleResult; @@ -6159,8 +6167,8 @@ namespace TestThrottle { cancel(): void; } - let func: SampleFunc; - let options: Options; + let func: SampleFunc = (a, b) => true; + let options: Options = {}; { let result: ResultFunc; @@ -6193,7 +6201,7 @@ namespace TestUnary { (a: number, b: string): boolean; } - let func: Func; + let func: Func = (a, b) => true; { let result: Func; @@ -6222,8 +6230,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: SampleValue, arg2: number, arg3: string) => boolean; - let value: SampleValue; - let wrapper: SampleWrapper; + let value: SampleValue = { a: 1, b: "", c: true }; + let wrapper: SampleWrapper = (a, b, c) => true; let result: SampleResult; result = _.wrap(value, wrapper); @@ -6234,8 +6242,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: number, arg2: number, arg3: string) => boolean; - let value: number; - let wrapper: SampleWrapper; + let value: number = 0; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; result = _(value).wrap(wrapper); @@ -6245,8 +6253,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: number[], arg2: number, arg3: string) => boolean; - let value: number[]; - let wrapper: SampleWrapper; + let value: number[] = []; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; result = _(value).wrap(wrapper); @@ -6256,8 +6264,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: SampleValue, arg2: number, arg3: string) => boolean; - let value: SampleValue; - let wrapper: SampleWrapper; + let value: SampleValue = { a: 1, b: "", c: true }; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; result = _(value).wrap(wrapper); @@ -6267,8 +6275,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: number, arg2: number, arg3: string) => boolean; - let value: number; - let wrapper: SampleWrapper; + let value: number = 0; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; result = _(value).chain().wrap(wrapper); @@ -6278,8 +6286,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: number[], arg2: number, arg3: string) => boolean; - let value: number[]; - let wrapper: SampleWrapper; + let value: number[] = []; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; result = _(value).chain().wrap(wrapper); @@ -6289,8 +6297,8 @@ namespace TestWrap { { type SampleWrapper = (arg1: SampleValue, arg2: number, arg3: string) => boolean; - let value: SampleValue; - let wrapper: SampleWrapper; + let value: SampleValue = { a: 1, b: "", c: true }; + let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; result = _(value).chain().wrap(wrapper); @@ -6428,7 +6436,7 @@ namespace TestCloneDeepWith { } { - let customizer: CloneDeepWithCustomizer; + let customizer: CloneDeepWithCustomizer = (x) => ""; let reslut: string; result = _.cloneDeepWith(42, customizer); @@ -6437,14 +6445,14 @@ namespace TestCloneDeepWith { } { - let customizer: CloneDeepWithCustomizer; + let customizer: CloneDeepWithCustomizer = (x) => ""; let result: _.LoDashExplicitWrapper; result = _(42).chain().cloneDeepWith(customizer); } { - let customizer: CloneDeepWithCustomizer; + let customizer: CloneDeepWithCustomizer = (x) => []; let reslut: string[]; result = _.cloneDeepWith([42], customizer); @@ -6453,14 +6461,14 @@ namespace TestCloneDeepWith { } { - let customizer: CloneDeepWithCustomizer; + let customizer: CloneDeepWithCustomizer = (x) => []; let result: _.LoDashExplicitArrayWrapper; result = _([42]).chain().cloneDeepWith(customizer); } { - let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}>; + let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let reslut: {a: {b: string;};}; result = _.cloneDeepWith<{a: {b: string;};}>({a: {b: 42}}, customizer); @@ -6469,7 +6477,7 @@ namespace TestCloneDeepWith { } { - let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}>; + let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let result: _.LoDashExplicitObjectWrapper<{a: {b: string;};}>; result = _({a: {b: 42}}).chain().cloneDeepWith<{a: {b: string;};}>(customizer); @@ -6483,7 +6491,7 @@ namespace TestCloneWith { } { - let customizer: CloneWithCustomizer; + let customizer: CloneWithCustomizer = (x) => ""; let reslut: string; result = _.cloneWith(42, customizer); @@ -6492,14 +6500,14 @@ namespace TestCloneWith { } { - let customizer: CloneWithCustomizer; + let customizer: CloneWithCustomizer = (x) => ""; let result: _.LoDashExplicitWrapper; result = _(42).chain().cloneWith(customizer); } { - let customizer: CloneWithCustomizer; + let customizer: CloneWithCustomizer = (x) => []; let reslut: string[]; result = _.cloneWith([42], customizer); @@ -6508,14 +6516,14 @@ namespace TestCloneWith { } { - let customizer: CloneWithCustomizer; + let customizer: CloneWithCustomizer = (x) => []; let result: _.LoDashExplicitArrayWrapper; result = _([42]).chain().cloneWith(customizer); } { - let customizer: CloneWithCustomizer<{a: {b: number;};}, {a: {b: string;};}>; + let customizer: CloneWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let reslut: {a: {b: string;};}; result = _.cloneWith<{a: {b: string;};}>({a: {b: 42}}, customizer); @@ -6524,7 +6532,7 @@ namespace TestCloneWith { } { - let customizer: CloneWithCustomizer<{a: {b: number;};}, {a: {b: string;};}>; + let customizer: CloneWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let result: _.LoDashExplicitObjectWrapper<{a: {b: string;};}>; result = _({a: {b: 42}}).chain().cloneWith<{a: {b: string;};}>(customizer); @@ -6605,7 +6613,7 @@ namespace TestGte { // _.isArguments namespace TestisArguments { { - let value: number|IArguments; + let value: number|IArguments = 0; if (_.isArguments(value)) { let result: IArguments = value; @@ -6636,7 +6644,7 @@ namespace TestisArguments { // _.isArray namespace TestIsArray { { - let value: number|string[]|boolean[]; + let value: number|string[]|boolean[] = []; if (_.isArray(value)) { let result: string[] = value; @@ -6672,7 +6680,7 @@ namespace TestIsArray { // _.isArrayBuffer namespace TestIsArrayBuffer { { - let value: ArrayBuffer|number; + let value: ArrayBuffer|number = 0; if (_.isArrayBuffer(value)) { let result: ArrayBuffer = value; @@ -6703,7 +6711,7 @@ namespace TestIsArrayBuffer { // _.isArrayLike namespace TestIsArrayLike { { - let value: number|string[]|boolean[]; + let value: number|string[]|boolean[] = []; if (_.isArrayLike(value)) { let result: string[] = value; @@ -6739,7 +6747,7 @@ namespace TestIsArrayLike { // _.isArrayLikeObject namespace TestIsArrayLikeObject { { - let value: number|string[]|boolean[]; + let value: number|string[]|boolean[] = []; if (_.isArrayLikeObject(value)) { let result: string[] = value; @@ -6775,7 +6783,7 @@ namespace TestIsArrayLikeObject { // _.isBoolean namespace TestIsBoolean { { - let value: number|boolean; + let value: number|boolean = 0; if (_.isBoolean(value)) { let result: boolean = value; @@ -6826,7 +6834,7 @@ namespace TestIsBuffer { // _.isDate namespace TestIsBoolean { { - let value: number|Date; + let value: number|Date = 0; if (_.isDate(value)) { let result: Date = value; @@ -6918,7 +6926,7 @@ namespace TestIsEqual { // _.isEqualWith namespace TestIsEqualWith { - let customizer: (value: any, other: any, indexOrKey?: number|string) => boolean; + let customizer = (value: any, other: any, indexOrKey?: number|string) => true; { let result: boolean; @@ -6937,8 +6945,9 @@ namespace TestIsEqualWith { // _.isError namespace TestIsError { + let x: any = 1; { - let value: number|Error; + let value: number|Error = x; if (_.isError(value)) { let result: Error = value; @@ -6953,7 +6962,7 @@ namespace TestIsError { custom: string } - let value: number|CustomError; + let value: number|CustomError = x; if (_.isError(value)) { let result: CustomError = value; @@ -7004,7 +7013,7 @@ namespace TestIsFinite { // _.isFunction namespace TestIsFunction { { - let value: number|Function; + let value: number|Function = () => {}; if (_.isFunction(value)) { let result: Function = value; @@ -7077,7 +7086,7 @@ namespace TestIsLength { // _.isMap namespace TestIsMap { { - let value: number|Map; + let value: number|Map = 0; if (_.isMap(value)) { let result: Map = value; @@ -7117,7 +7126,7 @@ namespace TestIsMatch { // _.isMatchWith namespace TestIsMatchWith { - let testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; + let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string) => true; let result: boolean; @@ -7149,7 +7158,7 @@ namespace TestIsNaN { // _.isNative namespace TestIsNative { { - let value: number|Function; + let value: number|Function = () => {}; if (_.isNative(value)) { let result: Function = value; @@ -7223,7 +7232,7 @@ namespace TestIsNull { // _.isNumber namespace TestIsNumber { { - let value: string|number; + let value: string|number = 0; if (_.isNumber(value)) { let result: number = value; @@ -7315,7 +7324,7 @@ namespace TestIsPlainObject { // _.isRegExp namespace TestIsRegExp { { - let value: number|RegExp; + let value: number|RegExp = /./; if (_.isRegExp(value)) { let result: RegExp = value; @@ -7367,7 +7376,7 @@ namespace TestIsSafeInteger { // _.isSet namespace TestIsSet { { - let value: number|Set; + let value: number|Set = 0; if (_.isSet(value)) { let result: Set = value; @@ -7398,7 +7407,7 @@ namespace TestIsSet { // _.isString namespace TestIsString { { - let value: number|string; + let value: number|string = ''; if (_.isString(value)) { let result: string = value; @@ -7489,7 +7498,7 @@ namespace TestIsWeakMap { { interface Obj { a: string }; - let value: number|WeakMap; + let value: number|WeakMap = 0; if (_.isWeakMap(value)) { let result: WeakMap = value; @@ -7520,7 +7529,7 @@ namespace TestIsWeakMap { // _.isWeakSet namespace TestIsWeakSet { { - let value: number|WeakSet; + let value: number|WeakSet = 0; if (_.isWeakSet(value)) { let result: WeakSet = value; @@ -7590,10 +7599,10 @@ namespace TestLte { // _.toArray namespace TestToArray { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; - let numericDictionary: _.NumericDictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; + let numericDictionary: _.NumericDictionary = {}; { let result: string[]; @@ -7824,8 +7833,8 @@ namespace TestFloor { // _.max namespace TestMax { - let array: number[]; - let list: _.List; + let array: number[] = []; + let list: _.List = []; let result: number; @@ -7838,12 +7847,12 @@ namespace TestMax { // _.maxBy namespace TestMaxBy { - let array: number[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: number[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: number, index: number, collection: _.List) => number; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; + let listIterator = (value: number, index: number, collection: _.List) => 0; + let dictionaryIterator = (value: number, key: string, collection: _.Dictionary) => 0; let result: number; @@ -7880,7 +7889,7 @@ namespace TestMaxBy { // _.mean namespace TestMean { - let array: number[]; + let array: number[] = []; let result: number; @@ -7891,8 +7900,8 @@ namespace TestMean { // _.min namespace TestMin { - let array: number[]; - let list: _.List; + let array: number[] = []; + let list: _.List = []; let result: number; @@ -7905,12 +7914,12 @@ namespace TestMin { // _.minBy namespace TestMinBy { - let array: number[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: number[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: number, index: number, collection: _.List) => number; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; + let listIterator = (value: number, index: number, collection: _.List) => 0; + let dictionaryIterator = (value: number, key: string, collection: _.Dictionary) => 0; let result: number; @@ -7967,12 +7976,12 @@ namespace TestRound { // _.sum namespace TestSum { - let array: number[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: number[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: number, index: number, collection: _.List) => number; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; + let listIterator = (value: number, index: number, collection: _.List) => 0; + let dictionaryIterator = (value: number, key: string, collection: _.Dictionary) => 0; { let result: number; @@ -8003,13 +8012,13 @@ namespace TestSum { // _.sumBy namespace TestSumBy { - let array: number[]; - let objectArray: { 'age': number }[]; + let array: number[] = []; + let objectArray: { 'age': number }[] = []; - let list: _.List; - let objectList: _.List<{ 'age': number }>; + let list: _.List = []; + let objectList: _.List<{ 'age': number }> = []; - let listIterator: (value: number, index: number, collection: _.List) => number; + let listIterator = (value: number, index: number, collection: _.List) => 0; { let result: number; @@ -8143,14 +8152,12 @@ namespace TestAssign { interface S4 { d: number }; interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; - - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; { let result: Obj; @@ -8270,14 +8277,14 @@ namespace TestAssignWith { interface S4 { d: number }; interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => 1; { let result: Obj; @@ -8382,14 +8389,14 @@ namespace TestAssignIn { interface S4 { d: number }; interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => 1; { let result: Obj; @@ -8509,14 +8516,14 @@ namespace TestAssignInWith { interface S4 { d: number }; interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => 1; { let result: Obj; @@ -8617,8 +8624,8 @@ namespace TestCreate { type SampleProto = {a: number}; type SampleProps = {b: string}; - let prototype: SampleProto; - let properties: SampleProps; + let prototype: SampleProto = { a: 1 }; + let properties: SampleProps = { b: "" }; { let result: {a: number; b: string}; @@ -8651,12 +8658,12 @@ namespace TestDefaults { interface S4 { d: number }; interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; { let result: Obj; @@ -8788,14 +8795,14 @@ namespace TestExtend { type S4 = { d: number }; type S5 = { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => 1; { let result: Obj; @@ -8915,14 +8922,14 @@ namespace TestExtendWith { type S4 = { d: number }; type S5 = { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj = { a: "" }; + let s1: S1 = { a: 1 }; + let s2: S2 = { b: 1 }; + let s3: S3 = { c: 1 }; + let s4: S4 = { d: 1 }; + let s5: S5 = { e: 1 }; - let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => 1; { let result: Obj; @@ -9036,7 +9043,7 @@ namespace TestExtendWith { // _.findKey namespace TestFindKey { { - let predicateFn: (value: any, key?: string, object?: {}) => boolean; + let predicateFn = (value: any, key: string, object: {}) => true; let result: string; result = _.findKey<{a: string;}>({a: ''}); @@ -9057,7 +9064,7 @@ namespace TestFindKey { } { - let predicateFn: (value: string, key?: string, collection?: _.Dictionary) => boolean; + let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: string; result = _.findKey({a: ''}, predicateFn); @@ -9066,7 +9073,7 @@ namespace TestFindKey { } { - let predicateFn: (value: any, key?: string, object?: {}) => boolean; + let predicateFn = (value: any, key: string, object: {}) => true; let result: _.LoDashExplicitWrapper; result = _<{a: string;}>({a: ''}).chain().findKey(); @@ -9079,7 +9086,7 @@ namespace TestFindKey { } { - let predicateFn: (value: string, key?: string, collection?: _.Dictionary) => boolean; + let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: _.LoDashExplicitWrapper; result = _<{a: string;}>({a: ''}).chain().findKey(predicateFn); @@ -9089,7 +9096,7 @@ namespace TestFindKey { // _.findLastKey namespace TestFindLastKey { { - let predicateFn: (value: any, key?: string, object?: {}) => boolean; + let predicateFn = (value: any, key: string, object: {}) => true; let result: string; result = _.findLastKey<{a: string;}>({a: ''}); @@ -9110,7 +9117,7 @@ namespace TestFindLastKey { } { - let predicateFn: (value: string, key?: string, collection?: _.Dictionary) => boolean; + let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: string; result = _.findLastKey({a: ''}, predicateFn); @@ -9119,7 +9126,7 @@ namespace TestFindLastKey { } { - let predicateFn: (value: any, key?: string, object?: {}) => boolean; + let predicateFn = (value: any, key: string, object: {}) => true; let result: _.LoDashExplicitWrapper; result = _<{a: string;}>({a: ''}).chain().findLastKey(); @@ -9132,7 +9139,7 @@ namespace TestFindLastKey { } { - let predicateFn: (value: string, key?: string, collection?: _.Dictionary) => boolean; + let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: _.LoDashExplicitWrapper; result = _<{a: string;}>({a: ''}).chain().findLastKey(predicateFn); @@ -9143,11 +9150,11 @@ namespace TestFindLastKey { namespace TestForIn { type SampleObject = {a: number; b: string; c: boolean;}; - let dictionary: _.Dictionary; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any; + let dictionary: _.Dictionary = {}; + let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any = (value: number, key: string, collection: _.Dictionary) => 1; - let object: SampleObject; - let objectIterator: (element: any, key?: string, collection?: any) => any; + let object: SampleObject = { a: 1, b: "", c: true }; + let objectIterator: (element: any, key?: string, collection?: any) => any = (element: any, key?: string, collection?: any) => 1; { let result: _.Dictionary; @@ -9182,11 +9189,11 @@ namespace TestForIn { namespace TestForInRight { type SampleObject = {a: number; b: string; c: boolean;}; - let dictionary: _.Dictionary; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any; + let dictionary: _.Dictionary = {}; + let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any = (value: number, key: string, collection: _.Dictionary) => 1; - let object: SampleObject; - let objectIterator: (element: any, key?: string, collection?: any) => any; + let object: SampleObject = { a: 1, b: "", c: true }; + let objectIterator: (element: any, key?: string, collection?: any) => any = (element: any, key?: string, collection?: any) => 1; { let result: _.Dictionary; @@ -9221,11 +9228,11 @@ namespace TestForInRight { namespace TestForOwn { type SampleObject = {a: number; b: string; c: boolean;}; - let dictionary: _.Dictionary; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any; + let dictionary: _.Dictionary = {}; + let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any = (value: number, key: string, collection: _.Dictionary) => 1; - let object: SampleObject; - let objectIterator: (element: any, key?: string, collection?: any) => any; + let object: SampleObject = { a: 1, b: "", c: true }; + let objectIterator: (element: any, key?: string, collection?: any) => any = (element: any, key?: string, collection?: any) => 1; { let result: _.Dictionary; @@ -9260,11 +9267,11 @@ namespace TestForOwn { namespace TestForOwnRight { type SampleObject = {a: number; b: string; c: boolean;}; - let dictionary: _.Dictionary; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any; + let dictionary: _.Dictionary = {}; + let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => any = (value: number, key: string, collection: _.Dictionary) => 1; - let object: SampleObject; - let objectIterator: (element: any, key?: string, collection?: any) => any; + let object: SampleObject = { a: 1, b: "", c: true }; + let objectIterator: (element: any, key?: string, collection?: any) => any = (element: any, key?: string, collection?: any) => 1; { let result: _.Dictionary; @@ -9299,7 +9306,7 @@ namespace TestForOwnRight { namespace TestFunctions { type SampleObject = {a: number; b: string; c: boolean;}; - let object: SampleObject; + let object: SampleObject = { a: 1, b: "", c: true }; { let result: string[]; @@ -9324,7 +9331,7 @@ namespace TestFunctions { namespace TestFunctionsIn { type SampleObject = {a: number; b: string; c: boolean;}; - let object: SampleObject; + let object: SampleObject = { a: 1, b: "", c: true }; { let result: string[]; @@ -9436,7 +9443,7 @@ namespace TestGet { namespace TestHas { type SampleObject = {a: number; b: string; c: boolean;}; - let object: SampleObject; + let object: SampleObject = { a: 1, b: "", c: true }; { let result: boolean; @@ -9466,7 +9473,7 @@ namespace TestHas { namespace TestHasIn { type SampleObject = {a: number; b: string; c: boolean;}; - let object: SampleObject; + let object: SampleObject = { a: 1, b: "", c: true }; { let result: boolean; @@ -9521,16 +9528,16 @@ namespace TestInvert { // _.invertBy namespace TestInvertBy { - let array: ({a: number;})[]; - let list: _.List<{a: number;}>; - let dictionary: _.Dictionary<{a: number;}>; - let numericDictionary: _.NumericDictionary<{a: number;}>; + let array: ({a: number;})[] = []; + let list: _.List<{a: number;}> = []; + let dictionary: _.Dictionary<{a: number;}> = {}; + let numericDictionary: _.NumericDictionary<{a: number;}> = {}; - let stringIterator: (value: string) => any; - let arrayIterator: (value: {a: number;}) => any; - let listIterator: (value: {a: number;}) => any; - let dictionaryIterator: (value: {a: number;}) => any; - let numericDictionaryIterator: (value: {a: number;}) => any; + let stringIterator: (value: string) => any = (value: string) => 1; + let arrayIterator: (value: {a: number;}) => any = (value: {a: number;}) => 1; + let listIterator: (value: {a: number;}) => any = (value: {a: number;}) => 1; + let dictionaryIterator: (value: {a: number;}) => any = (value: {a: number;}) => 1; + let numericDictionaryIterator: (value: {a: number;}) => any = (value: {a: number;}) => 1; { let result: _.Dictionary; @@ -9616,7 +9623,7 @@ namespace TestInvertBy { // _.keys namespace TestKeys { - let object: _.Dictionary; + let object: _.Dictionary = {}; { let result: string[]; @@ -9639,7 +9646,7 @@ namespace TestKeys { // _.keysIn namespace TestKeysIn { - let object: _.Dictionary; + let object: _.Dictionary = {}; { let result: string[]; @@ -9662,12 +9669,12 @@ namespace TestKeysIn { // _.mapKeys namespace TestMapKeys { - let array: TResult[]; - let list: _.List; - let dictionary: _.Dictionary; + let array: TResult[] = []; + let list: _.List = []; + let dictionary: _.Dictionary = {}; - let listIterator: (value: TResult, index: number, collection: _.List) => string; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => string; + let listIterator = (value: TResult, index: number, collection: _.List) => ""; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => ""; { let result: _.Dictionary; @@ -9828,7 +9835,7 @@ namespace TestMergeWith { type ExpectedResult = { a: number, b: string }; let result: ExpectedResult; - let customizer: (value: any, srcValue: any, key?: string, object?: InitialValue, source?: MergingValue) => any; + let customizer: (value: any, srcValue: any, key?: string, object?: InitialValue, source?: MergingValue) => any = (value: any, srcValue: any, key?: string, object?: InitialValue, source?: MergingValue) => 1; // Test for basic merging result = _.mergeWith(initialValue, mergingValue, customizer); @@ -9883,7 +9890,7 @@ namespace TestOmit { // _.omitBy namespace TestOmitBy { - let predicate: (element: any, key: string, collection: any) => boolean; + let predicate = (element: any, key: string, collection: any) => true; { let result: TResult; @@ -9938,7 +9945,7 @@ namespace TestPick { // _.pickBy namespace TestPickBy { - let predicate: (element: any, key: string, collection: any) => boolean; + let predicate = (element: any, key: string, collection: any) => true; { let result: TResult; @@ -10075,8 +10082,8 @@ namespace TestSet { type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject; - let value: number; + let object: SampleObject = { a: {} }; + let value: number = 0; { let result: SampleResult; @@ -10117,9 +10124,9 @@ namespace TestSetWith { type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject; - let value: number; - let customizer: (value: any, key: string, object: SampleObject) => number; + let object: SampleObject = { a: {} }; + let value: number = 0; + let customizer = (value: any, key: string, object: SampleObject) => 0; { let result: SampleResult; @@ -10171,7 +10178,7 @@ namespace TestSetWith { // _.toPairs namespace TestToPairs { - let object: _.Dictionary; + let object: _.Dictionary = {}; { let result: [string, any][]; @@ -10212,7 +10219,7 @@ namespace TestToPairs { // _.toPairsIn namespace TestToPairsIn { - let object: _.Dictionary; + let object: _.Dictionary = {}; { let result: [string, any][]; @@ -10253,12 +10260,12 @@ namespace TestToPairsIn { // _.transform namespace TestTransform { - let array: number[]; - let dictionary: _.Dictionary; + let array: number[] = []; + let dictionary: _.Dictionary = {}; { - let iterator: (acc: TResult[], curr: number, index?: number, arr?: number[]) => void; - let accumulator: TResult[]; + let iterator = (acc: TResult[], curr: number, index?: number, arr?: number[]) => {}; + let accumulator: TResult[] = []; let result: TResult[]; result = _.transform(array); @@ -10271,8 +10278,8 @@ namespace TestTransform { } { - let iterator: (acc: _.Dictionary, curr: number, index?: number, arr?: number[]) => void; - let accumulator: _.Dictionary; + let iterator = (acc: _.Dictionary, curr: number, index?: number, arr?: number[]) => {}; + let accumulator: _.Dictionary = {}; let result: _.Dictionary; result = _.transform(array, iterator); @@ -10283,8 +10290,8 @@ namespace TestTransform { } { - let iterator: (acc: _.Dictionary, curr: number, key?: string, dict?: _.Dictionary) => void; - let accumulator: _.Dictionary; + let iterator = (acc: _.Dictionary, curr: number, key?: string, dict?: _.Dictionary) => {}; + let accumulator: _.Dictionary = {}; let result: _.Dictionary; result = _.transform(dictionary); @@ -10297,8 +10304,8 @@ namespace TestTransform { } { - let iterator: (acc: TResult[], curr: number, key?: string, dict?: _.Dictionary) => void; - let accumulator: TResult[]; + let iterator = (acc: TResult[], curr: number, key?: string, dict?: _.Dictionary) => {}; + let accumulator: TResult[] = []; let result: TResult[]; result = _.transform(dictionary, iterator); @@ -10313,7 +10320,7 @@ namespace TestTransform { namespace TestUnset { type SampleObject = {a: {b: string; c: boolean}}; - let object: SampleObject; + let object: SampleObject = { a: { b: "", c: true } }; { let result: boolean; @@ -10342,8 +10349,8 @@ namespace TestUpdate { type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject; - let updater: (value: any) => number; + let object: SampleObject = { a: {} }; + let updater = (value: any) => 0; { let result: SampleResult; @@ -10415,10 +10422,10 @@ namespace TestValues { } { - let dict: _.Dictionary; - let numDict: _.NumericDictionary; - let list: _.List; - let object: {a: SampleObject}; + let dict: _.Dictionary = {}; + let numDict: _.NumericDictionary = {}; + let list: _.List = []; + let object: {a: SampleObject} = { a: { a: {} } }; let result: SampleObject[]; result = _.values(dict); @@ -10457,10 +10464,10 @@ namespace TestValues { } { - let dict: _.Dictionary; - let numDict: _.NumericDictionary; - let list: _.List; - let object: {a: SampleObject}; + let dict: _.Dictionary = {}; + let numDict: _.NumericDictionary = {}; + let list: _.List = []; + let object: {a: SampleObject} = { a: { a: {} } }; let result: _.LoDashImplicitArrayWrapper; result = _(dict).values(); @@ -10499,10 +10506,10 @@ namespace TestValues { } { - let dict: _.Dictionary; - let numDict: _.NumericDictionary; - let list: _.List; - let object: {a: SampleObject}; + let dict: _.Dictionary = {}; + let numDict: _.NumericDictionary = {}; + let list: _.List = []; + let object: {a: SampleObject} = { a: { a: {} } }; let result: _.LoDashExplicitArrayWrapper; result = _(dict).chain().values(); @@ -10514,7 +10521,7 @@ namespace TestValues { // _.valuesIn namespace TestValuesIn { - let object: _.Dictionary; + let object: _.Dictionary = {}; { let result: TResult[]; @@ -10956,7 +10963,7 @@ namespace TestTemplate { interpolate?: RegExp; sourceURL?: string; variable?: string; - }; + } = {}; { let result: TemplateExecutor; @@ -11171,7 +11178,7 @@ namespace TestWords { // _.attempt namespace TestAttempt { - let func: (...args: any[]) => {a: string}; + let func: (...args: any[]) => {a: string} = (...args) => ({ a: "" }); { let result: {a: string}|Error; @@ -11487,7 +11494,7 @@ namespace TestIteratee { // _.matches namespace TestMatches { - let source: TResult; + let source: TResult = { a: 1, b: "", c: true }; { let result: (value: any) => boolean; @@ -11512,8 +11519,8 @@ namespace TestMatches { // _.matchesProperty namespace TestMatches { - let path: {toString(): string;}|{toString(): string;}[]; - let source: TResult; + let path: {toString(): string;}|{toString(): string;}[] = []; + let source: TResult = { a: 1, b: "", c: true }; { let result: (value: any) => boolean; @@ -11642,7 +11649,7 @@ namespace TestMethodOf { type SampleObject = { a: { b(): TResult }[] }; type ResultFn = (path: _.StringRepresentable|_.StringRepresentable[]) => TResult; - let object: SampleObject; + let object: SampleObject = { a: [] }; { let result: ResultFn; @@ -11679,8 +11686,8 @@ namespace TestMethodOf { // _.mixin namespace TestMixin { - let source: _.Dictionary; - let options: {chain?: boolean}; + let source: _.Dictionary = {}; + let options: {chain?: boolean} = {}; { let result: TResult; @@ -11909,7 +11916,7 @@ namespace TestPropertyOf { } } - let object: SampleObject; + let object: SampleObject = { a: { b: [] } }; { let result: (path: string|string[]) => any; @@ -12095,7 +12102,7 @@ namespace TestRangeRight { // _.times namespace TestTimes { - let iteratee: (num: number) => TResult; + let iteratee: (num: number) => TResult = (num: number) => ({ a: 1, b: "", c: true }); { let result: number[]; diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index c0730d6661..88cd24b85a 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -299,7 +299,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/loopback-boot/loopback-boot-tests.ts b/types/loopback-boot/loopback-boot-tests.ts index 5b0e8d54a9..5de95d00c6 100644 --- a/types/loopback-boot/loopback-boot-tests.ts +++ b/types/loopback-boot/loopback-boot-tests.ts @@ -3,18 +3,18 @@ import * as boot from 'loopback-boot'; import * as cookieParser from 'cookie-parser'; class Server { - app: loopback.LoopBackApplication; + app: loopback.LoopBackApplication; - static boostrap(): Server { - return new Server(); - } - constructor() { - this.app = loopback(); + static boostrap(): Server { + return new Server(); + } + constructor() { + this.app = loopback(); - this.app.use(cookieParser()); + this.app.use(cookieParser()); - this.config(); - } + this.config(); + } private config(): void { boot(this.app, __dirname, (err: Error) => { diff --git a/types/mailgen/index.d.ts b/types/mailgen/index.d.ts index 1db097ffad..40eca3e1fd 100644 --- a/types/mailgen/index.d.ts +++ b/types/mailgen/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for mailgen 2.0 // Project: https://github.com/eladnava/mailgen#readme -// Definitions by: Kiet Thanh Vo +// Definitions by: Kiet Thanh Vo , Jordan Farrer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import Option = Mailgen.Option; import Content = Mailgen.Content; @@ -29,6 +29,7 @@ declare namespace Mailgen { name: string; link: string; logo?: string; + copyright?: string; } interface Content { @@ -36,10 +37,32 @@ declare namespace Mailgen { } interface ContentBody { - name: string; - intro: string; - action?: Action; - outro: string; + name?: string; + greeting?: string; + signature?: string; + title?: string; + intro?: string | string[]; + action?: Action | Action[]; + table?: Table; + dictionary?: any; + goToAction?: GoToAction; + outro?: string | string[]; + } + + interface Table { + data: any[]; + columns?: ColumnOptions[]; + } + + interface ColumnOptions { + customWidth: any; + customAlignment: any; + } + + interface GoToAction { + text: string; + link: string; + description: string; } interface Action { diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index b7a9064f86..99c9854791 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.30.0 +// Type definitions for Mapbox GL JS v0.35.1 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,7 @@ declare namespace mapboxgl { let accessToken: string; let version: string; export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + export function setRTLTextPlugin(pluginURL: string, callback: Function): void; /** * Map @@ -50,7 +51,7 @@ declare namespace mapboxgl { queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; - querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; setStyle(style: mapboxgl.Style | string): this; @@ -58,10 +59,18 @@ declare namespace mapboxgl { addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + isSourceLoaded(id: string): boolean; + removeSource(id: string): this; getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: {width?: number, height?: number, pixelRatio?: number}): this; + + removeImage(name: string): this; + + loadImage(url: string, callback: Function): this; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -84,6 +93,10 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; + setLight(options: mapboxgl.Light, lightOptions: any): this; + + getLight(): mapboxgl.Light; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +147,7 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; - fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: Point|number[],maxZoom?: number }, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -142,6 +155,8 @@ declare namespace mapboxgl { flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + isMoving(): boolean; + stop(): this; scrollZoom: ScrollZoomHandler; @@ -201,6 +216,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + logoPosition?: boolean; + /** If set, the map is constrained to the given bounds. */ maxBounds?: mapboxgl.LngLatBounds | number[][]; @@ -215,6 +232,10 @@ declare namespace mapboxgl { pitch?: number; + refreshExpiredTiles?: boolean; + + renderWorldCopies?: boolean; + /** If true, enable the "scroll to zoom" interaction */ scrollZoom?: boolean; @@ -231,6 +252,13 @@ declare namespace mapboxgl { zoom?: number; } + export class PaddingOptions extends Evented { + top: number; + bottom: number; + left: number; + right: number; + } + /** * BoxZoomHandler */ @@ -368,7 +396,7 @@ declare namespace mapboxgl { * Attribution */ export class AttributionControl extends Control { - constructor(); + constructor(options?: {compact?: boolean}); } /** @@ -378,6 +406,13 @@ declare namespace mapboxgl { constructor(options?: {maxWidth?: number, unit?: string}) } + /** + * Fullscreen + */ + export class FullscreenControl extends Control { + constructor(); + } + /** * Popup */ @@ -440,7 +475,7 @@ declare namespace mapboxgl { } export interface Source { - type: "vector" | "raster" | "geojson" | "image" | "video"; + type: "vector" | "raster" | "geojson" | "image" | "video" | "canvas"; } /** @@ -511,6 +546,29 @@ declare namespace mapboxgl { coordinates?: number[][]; } + /** + * CanvasSource + */ + export class CanvasSource implements Source, CanvasSourceOptions { + type: "canvas"; + + coordinates: number[][]; + + canvas: string; + + getCanvas(): HTMLCanvasElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface CanvasSourceOptions { + coordinates: number[][]; + + animate?: boolean; + + canvas: string; + } + interface VectorSource extends Source { type: "vector"; url?: string; @@ -540,6 +598,8 @@ declare namespace mapboxgl { /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ wrap(): mapboxgl.LngLat; + wrapToBestWorld(center: mapboxgl.LngLat): mapboxgl.LngLat; + /** Return a LngLat as an array */ toArray(): number[]; @@ -665,8 +725,12 @@ declare namespace mapboxgl { export class Evented { on(type: string, listener: Function): this; + on(type: string, layer: string, listener: Function): this; + off(type?: string | any, listener?: Function): this; + off(type?: string | any, layer?: string, listener?: Function): this; + once(type: string, listener: Function): this; fire(type: string, data?: mapboxgl.EventData | Object): this; @@ -810,7 +874,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; metadata?: any; ref?: string; @@ -834,6 +898,7 @@ declare namespace mapboxgl { property?: string; base?: number; type?: "identity" | "exponential" | "interval" | "categorical"; + default?: any; "colorSpace"?: "rgb" | "lab" | "interval"; } @@ -881,14 +946,14 @@ declare namespace mapboxgl { "line-round-limit"?: number; } export interface LinePaint { - "line-opacity"?: number; + "line-opacity"?: number | StyleFunction; "line-color"?: string| StyleFunction; "line-translate"?: number[]; "line-translate-anchor"?: "map" | "viewport"; "line-width"?: number; - "line-gap-width"?: number; - "line-offset"?: number; - "line-blur"?: number; + "line-gap-width"?: number | StyleFunction; + "line-offset"?: number | StyleFunction; + "line-blur"?: number | StyleFunction; "line-dasharray"?: number[]; "line-dasharray-transition"?: Transition; "line-pattern"?: string; @@ -904,29 +969,29 @@ declare namespace mapboxgl { "icon-ignore-placement"?: boolean; "icon-optional"?: boolean; "icon-rotation-alignment"?: "map" | "viewport" | "auto"; - "icon-size"?: number; + "icon-size"?: number | StyleFunction; "icon-text-fit"?: "none" | "both" | "width" | "height"; "icon-text-fit-padding"?: number[]; - "icon-image"?: string; + "icon-image"?: string | StyleFunction; "icon-rotate"?: number | StyleFunction; "icon-padding"?: number; "icon-keep-upright"?: boolean; "icon-offset"?: number[] | StyleFunction; "text-pitch-alignment"?: "map" | "viewport" | "auto"; "text-rotation-alignment"?: "map" | "viewport" | "auto"; - "text-field"?: string; + "text-field"?: string | StyleFunction; "text-font"?: string | string[]; - "text-size"?: number; + "text-size"?: number | StyleFunction; "text-max-width"?: number; "text-line-height"?: number; "text-letter-spacing"?: number; "text-justify"?: "left" | "center" | "right"; "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; "text-max-angle"?: number; - "text-rotate"?: number; + "text-rotate"?: number | StyleFunction; "text-padding"?: number; "text-keep-upright"?: boolean; - "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-transform"?: "none" | "uppercase" | "lowercase" | StyleFunction; "text-offset"?: number[]; "text-allow-overlap"?: boolean; "text-ignore-placement"?: boolean; @@ -934,18 +999,18 @@ declare namespace mapboxgl { } export interface SymbolPaint { - "icon-opacity"?: number; - "icon-color"?: string; - "icon-halo-color"?: string; - "icon-halo-width"?: number; - "icon-halo-blur"?: number; + "icon-opacity"?: number | StyleFunction; + "icon-color"?: string | StyleFunction; + "icon-halo-color"?: string | StyleFunction; + "icon-halo-width"?: number | StyleFunction; + "icon-halo-blur"?: number | StyleFunction; "icon-translate"?: number[]; "icon-translate-anchor"?: "map" | "viewport"; - "text-opacity"?: number; - "text-color"?: "string"; - "text-halo-color"?: "string"; - "text-halo-width"?: number; - "text-halo-blur"?: number; + "text-opacity"?: number | StyleFunction; + "text-color"?: string | StyleFunction; + "text-halo-color"?: string | StyleFunction; + "text-halo-width"?: number | StyleFunction; + "text-halo-blur"?: number | StyleFunction; "text-translate"?: number[]; "text-translate-anchor"?: "map" | "viewport"; } diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts new file mode 100644 index 0000000000..f2d3722a3d --- /dev/null +++ b/types/markdown-it-container/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for MarkdownItContainer (markdown-it-container) 2.0 +// Project: https://github.com/markdown-it/markdown-it-container +// Definitions by: Vyacheslav Demot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { MarkdownIt, Token, Renderer } from 'markdown-it'; + +declare namespace markdownItContainer { + interface ContainerOpts { + marker?: string; + validate?(params: string): boolean; + render?(tokens: Token[], index: number, options: any, env: any, self: Renderer): void; + } + + function container_plugin(md: MarkdownIt, name: string, opts: ContainerOpts): void; +} + +declare var MarkdownItContainer: typeof markdownItContainer.container_plugin; +export = MarkdownItContainer; diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts new file mode 100644 index 0000000000..f3ef2dbba1 --- /dev/null +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -0,0 +1,32 @@ +import * as MarkdownIt from "markdown-it"; +import MarkdownItContainer = require("markdown-it-container"); + +const md = new MarkdownIt(); + +md.use(MarkdownItContainer, 'spoiler', { + validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), + render: (tokens: MarkdownIt.Token[], index: number) => { + const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); + const onClick = + "this.parentNode.classList.toggle('_expanded');" + + "event.preventDefault();"; + + if (tokens[index].nesting === 1) { + return ( + '
\n' + + '
\n' + + md.utils.escapeHtml(match && match[1] || '') + '\n' + + '
\n' + + '
\n' + ); + } else { + return '
\n'; + } + } +}); + +const src = `:::spoiler This Is Spoiler Title +Here is spoiler content. +:::`; + +md.render(src); diff --git a/types/markdown-it-container/tsconfig.json b/types/markdown-it-container/tsconfig.json new file mode 100644 index 0000000000..270b4284f0 --- /dev/null +++ b/types/markdown-it-container/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "markdown-it-container-tests.ts" + ] +} \ No newline at end of file diff --git a/types/markdown-it-container/tslint.json b/types/markdown-it-container/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/markdown-it-container/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index b6919280d3..47c124595e 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for material-ui v0.17.4 +// Type definitions for material-ui v0.17.51 // Project: https://github.com/callemall/material-ui -// Definitions by: Nathan Brown , Igor Belagorudsky , Ali Taheri Moghaddar , Oliver Herrmann , Daniel Roth +// Definitions by: Nathan Brown , Igor Belagorudsky , Ali Taheri Moghaddar , Oliver Herrmann , Daniel Roth , Aurelién Allienne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -661,6 +661,7 @@ declare namespace __MaterialUI { interface FlatButtonProps extends React.DOMAttributes<{}>, SharedEnhancedButtonProps { // is the element that get the 'other' properties backgroundColor?: string; + className?: string; disabled?: boolean; fullWidth?: boolean; hoverColor?: string; @@ -822,6 +823,8 @@ declare namespace __MaterialUI { titleColor?: string; titleStyle?: React.CSSProperties; className?: string; + openIcon?: React.ReactNode; + closeIcon?: React.ReactNode; } export class CardHeader extends React.Component { } @@ -1016,7 +1019,7 @@ declare namespace __MaterialUI { overlayStyle?: React.CSSProperties; style?: React.CSSProperties; swipeAreaWidth?: number; - width?: number; + width?: number | string; zDepth?: number; } export class Drawer extends React.Component { @@ -1342,10 +1345,12 @@ declare namespace __MaterialUI { iconStyle?: React.CSSProperties; id?: string; labelStyle?: React.CSSProperties; + multiple?: boolean; onBlur?: React.FocusEventHandler<{}>; onChange?: (e: TouchTapEvent, index: number, menuItemValue: any) => void; onFocus?: React.FocusEventHandler<{}>; selectFieldRoot?: React.CSSProperties; + selectionRenderer?: (value: any) => React.ReactNode; style?: React.CSSProperties; underlineDisabledStyle?: React.CSSProperties; underlineFocusStyle?: React.CSSProperties; diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index d1a6397f42..a0d8d32d92 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -1662,7 +1662,7 @@ class DrawerOpenRightExample extends React.Component<{}, {open?: boolean}> { label="Toggle Drawer" onTouchTap={this.handleToggle} /> - + @@ -3453,6 +3453,115 @@ class SelectFieldExampleError extends React.Component<{}, {value?: number}> { } } +const names = [ + 'Oliver Hansen', + 'Van Henry', + 'April Tucker', + 'Ralph Hubbard', + 'Omar Alexander', + 'Carlos Abbott', + 'Miriam Wagner', + 'Bradley Wilkerson', + 'Virginia Andrews', + 'Kelly Snyder', +]; + +class SelectFieldExampleMultiSelect extends React.Component<{}, {values?: string[]}> { + + constructor(props) { + super(props); + this.state = {values: []}; + } + + handleChange = (event, index, values) => this.setState({values}); + + menuItems(values) { + return names.map((name) => ( + + )); + } + + render() { + const {values} = this.state; + return ( + + {this.menuItems(values)} + + ); + } +} + +const persons = [ + {value: 0, name: 'Oliver Hansen'}, + {value: 1, name: 'Van Henry'}, + {value: 2, name: 'April Tucker'}, + {value: 3, name: 'Ralph Hubbard'}, + {value: 4, name: 'Omar Alexander'}, + {value: 5, name: 'Carlos Abbott'}, + {value: 6, name: 'Miriam Wagner'}, + {value: 7, name: 'Bradley Wilkerson'}, + {value: 8, name: 'Virginia Andrews'}, + {value: 9, name: 'Kelly Snyder'}, +]; + +class SelectFieldExampleSelectionRenderer extends React.Component<{}, {values?: string[]}> { + + constructor(props) { + super(props); + this.state = {values: []}; + } + + handleChange = (event, index, values) => this.setState({values}); + + selectionRenderer = (values) => { + switch (values.length) { + case 0: + return ''; + case 1: + return persons[values[0]].name; + default: + return `${values.length} names selected`; + } + } + + menuItems(persons) { + return persons.map((person) => ( + = 0} + value={person.value} + primaryText={person.name} + /> + )); + } + + render() { + return ( + + {this.menuItems(persons)} + + ); + } +} + // "http://www.material-ui.com/#/components/slider" const SliderExampleSimple = () => ( diff --git a/types/memcached/index.d.ts b/types/memcached/index.d.ts index 24aa6beb3e..3c46efe396 100644 --- a/types/memcached/index.d.ts +++ b/types/memcached/index.d.ts @@ -13,25 +13,11 @@ declare class Memcached extends events.EventEmitter { static config: Memcached.options; /** - * Connect to a single server. - * @param location Server location e.g. "127.0.0.1:11211" + * Connect to a single Memcached server or cluster + * @param location Server locations * @param options options */ - constructor(location: string, options?: Memcached.options); - - /** - * Connect to a cluster of Memcached servers. - * @param location Server locations e.g. ["127.0.0.1:11211","127.0.0.1:11212"] - * @param options options - */ - constructor(location: string[], options?: Memcached.options); - - /** - * Connect to servers with weight. - * @param location Server locations e.g. {"127.0.0.1:11211": 1,"127.0.0.1:11212": 2} - * @param options options - */ - constructor(location: {[server: string]: number}, options ?: Memcached.options); + constructor(location: Memcached.Location, options?: Memcached.options); /** * Touches the given key. @@ -185,29 +171,9 @@ declare class Memcached extends events.EventEmitter { flush(cb: (this: undefined, err: any, results: boolean[]) => void): void; /** - * a issue occurred on one a server, we are going to attempt a retry next. + * Register event listener */ - on(event: "issue", cb: (err: Memcached.IssueData) => void): this; - - /** - * a server has been marked as failure or dead. - */ - on(event: "failure", cb: (err: Memcached.IssueData) => void): this; - - /** - * we are going to attempt to reconnect the to the failed server. - */ - on(event: "reconnecting", cb: (err: Memcached.IssueData) => void): this; - - /** - * successfully reconnected to the memcached server. - */ - on(event: "reconnect", cb: (err: Memcached.IssueData) => void): this; - - /** - * removing the server from our consistent hashing. - */ - on( event: "remove", cb: (err: Memcached.IssueData) => void): this; + on(event: Memcached.EventNames, cb: (err: Memcached.IssueData) => void): this; /** * Closes all active memcached connections. @@ -260,6 +226,31 @@ declare namespace Memcached { s: number; } + /** + *
    + *
  • issue a issue occurred on a server, we are going to attempt a retry next.
  • + *
  • failure a server has been marked as failure or dead.
  • + *
  • reconnecting we are going to attempt to reconnect the to the failed server.
  • + *
  • reconnect successfully reconnected to the memcached server.
  • + *
  • remove removing the server from our consistent hashing.
  • + *
+ */ + type EventNames = "issue" | "failure" | "reconnecting" | "reconnect" | "remove"; + + /** + * Declaration for single server or Memcached cluster location + * + * to connect to a single server use + * "127.0.0.1:11211" + * + * to connect to a cluster of Memcached servers use + * ["127.0.0.1:11211","127.0.0.1:11212"] + * + * to connect to servers with weight use + * {"127.0.0.1:11211": 1,"127.0.0.1:11212": 2} + */ + type Location = string | string[] | {[server: string]: number}; + interface options { /** * 250, the maximum key size allowed. diff --git a/types/memcached/tslint.json b/types/memcached/tslint.json index 08b1465cd6..f93cf8562a 100644 --- a/types/memcached/tslint.json +++ b/types/memcached/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "unified-signatures": false - } + "extends": "dtslint/dt.json" } diff --git a/types/microsoft-ajax/index.d.ts b/types/microsoft-ajax/index.d.ts index 6c6d34dc9d..27aeeb441f 100644 --- a/types/microsoft-ajax/index.d.ts +++ b/types/microsoft-ajax/index.d.ts @@ -1406,6 +1406,31 @@ declare namespace Sys { */ static nullWebRequest: string; + /** + * @return "'{0}' is not an event." + */ + static undefinedEvent: string; + + /** + * @return "Handler must be a function." + */ + static eventHandlerNotFunction: string; + + /** + * @return "'{0}' is not a property or an existing field." + */ + static propertyUndefined: string; + + /** + * @return "'{0}' is not an Array property." + */ + static propertyNotAnArray: string; + + /** + * @return "'{0}' is not a writable property." + */ + static propertyNotWritable: string; + //#endregion } diff --git a/types/microsoft-ajax/microsoft-ajax-tests.ts b/types/microsoft-ajax/microsoft-ajax-tests.ts index fb0ebff654..d392dbbe2c 100644 --- a/types/microsoft-ajax/microsoft-ajax-tests.ts +++ b/types/microsoft-ajax/microsoft-ajax-tests.ts @@ -548,6 +548,11 @@ function Sys_Res_Tests() { var invokeCalledTwice = Sys.Res.invokeCalledTwice; var notImplemented = Sys.Res.notImplemented; var nullWebRequest = Sys.Res.nullWebRequest; + var undefinedEvent = Sys.Res.undefinedEvent; + var eventHandlerNotFunction = Sys.Res.eventHandlerNotFunction; + var propertyUndefined = Sys.Res.propertyUndefined; + var propertyNotAnArray = Sys.Res.propertyNotAnArray; + var propertyNotWritable = Sys.Res.propertyNotWritable; } function Sys_StringBuilder_Tests() { diff --git a/types/mime-db/index.d.ts b/types/mime-db/index.d.ts new file mode 100644 index 0000000000..cf46a0c593 --- /dev/null +++ b/types/mime-db/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for mime-db 1.27 +// Project: https://github.com/jshttp/mime-db +// Definitions by: AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Data Structure + * If unknown, every property could be undefined. + * @see {@link https://github.com/jshttp/mime-db#data-structure} + */ +export interface DataStructure { + /** where the mime type is defined. If not set, it's probably a custom media type. */ + source?: string; + /** known extensions associated with this mime type. */ + extensions?: string[]; + /** whether a file of this type can be gzipped. */ + compressible?: boolean; + /** the default charset associated with this type, if any. */ + charset?: string; +} diff --git a/types/mime-db/tsconfig.json b/types/mime-db/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/mime-db/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/mimos/index.d.ts b/types/mimos/index.d.ts new file mode 100644 index 0000000000..9d000b0ce9 --- /dev/null +++ b/types/mimos/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for mimos 3.0 +// Project: https://github.com/hapijs/mimos +// Definitions by: AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import {DataStructure as MimeDbDataStructure} from 'mime-db'; + +/** + * + * @see {@link https://github.com/hapijs/mimos#new-mimosoptions} + */ +export interface MimosOptions { + /** + * an object hash that is merged into the built in mime information specified here {@link https://github.com/jshttp/mime-db}. Each key value pair represents a single mime object. Each override value should follow this schema: + * * the key is the lower-cased correct mime-type. (Ex. "application/javascript"). + * * the value should an object @see MimosOptionsValue + */ + override: {[index: string]: MimosOptionsValue}; +} + +export interface MimosOptionsValue extends MimeDbDataStructure { + /** specify the type value of result objects, defaults to key. See the example below for more clarification. */ + type?: string; + /** method with signature function(mime) when this mime type is found in the database, this function will run. This allows you make customizations to mime based on developer criteria. */ + predicate?: (mime: MimosOptionsValue) => MimosOptionsValue; +} diff --git a/types/mimos/tsconfig.json b/types/mimos/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/mimos/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 1115d7c1f5..46fbb061ab 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -61,11 +61,11 @@ declare namespace Mithril { trust(html: string): Vnode; } - interface RouteResolver { + interface RouteResolver { /** The onmatch hook is called when the router needs to find a component to render. */ - render?(this: State, vnode: Vnode): Children; + onmatch?(this: this, args: Attrs, requestedPath: string): Component | Promise | void; /** The render method is called on every redraw for a matching route. */ - onmatch?(args: Params, requestedPath: string): Component | Promise | void; + render?(this: this, vnode: Vnode): Children; } /** This represents a key-value mapping linking routes to components. */ @@ -232,7 +232,7 @@ declare namespace Mithril { /** The onremove hook is called before a DOM element is removed from the document. */ onupdate?(vnode: VnodeDOM): any; /** Creates a view out of virtual elements. */ - view(vnode: CVnode): Children | null | void; + view(vnode: Vnode): Children | null | void; } /** diff --git a/types/mithril/test/test-class-component.ts b/types/mithril/test/test-class-component.ts index 7c1348683e..19f3aa343a 100644 --- a/types/mithril/test/test-class-component.ts +++ b/types/mithril/test/test-class-component.ts @@ -1,5 +1,5 @@ import * as m from 'mithril'; -import {ClassComponent, CVnode, CVnodeDOM} from 'mithril'; +import {ClassComponent, Vnode, CVnode, CVnodeDOM} from 'mithril'; /////////////////////////////////////////////////////////// // 0. @@ -95,12 +95,13 @@ class Comp4 implements ClassComponent { add(num: number) { this.count += num; } - view({attrs}: CVnode) { + view(vnode: Vnode) { return [ - m('h1', `This ${attrs.name} has been clicked ${this.count} times`), + m('h1', `This ${vnode.attrs.name} has been clicked ${this.count} times`), m('button', { - onclick: () => this.add(1) + // Can access 'this' via vnode.state + onclick: () => vnode.state.add(1) }, "Click me") ]; @@ -129,7 +130,7 @@ export interface Attrs { export default class MyComponent implements ClassComponent { count = 0; - view({attrs}: CVnode) { + view({attrs}: Vnode) { return m('span', `name: ${attrs.name}, count: ${this.count}`); } } diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 5e584a8184..b18a92212c 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -1,4 +1,4 @@ -import {Component} from 'mithril'; +import {Component, Comp, RouteResolver} from 'mithril'; import * as h from 'mithril/hyperscript'; import * as route from 'mithril/route'; @@ -14,6 +14,39 @@ const component2 = { } } as Component<{title: string}, {}>; +interface Attrs { + id: string; +} + +interface State { + text: string; +} + +const component3: Comp = { + text: "Uninitialized", + oninit({state}) { + state.text = "Initialized"; + }, + view({attrs}) { + return h('p', 'id: ' + attrs.id); + } +}; + +// RouteResolver example using Attrs type and this context +const routeResolver: RouteResolver & {message: string} = { + message: "", + onmatch(attrs, path) { + this.message = "Match"; + const id: string = attrs.id; + return component3; + }, + render(vnode) { + this.message = "Render"; + vnode.key = vnode.attrs.id; + return vnode; + } +}; + route(document.body, '/', { '/': component1, '/test1': { @@ -41,7 +74,8 @@ route(document.body, '/', { resolve(component2); }); } - } + }, + 'test5/:id': routeResolver }); route.prefix('/app'); diff --git a/types/moment-duration-format/index.d.ts b/types/moment-duration-format/index.d.ts index 41b36bc34d..76eb839cbd 100644 --- a/types/moment-duration-format/index.d.ts +++ b/types/moment-duration-format/index.d.ts @@ -15,7 +15,7 @@ declare module "moment" { interface DurationFormatSettings { template?: string; precision?: number; - trim?: boolean; + trim?: boolean | "right"; forceLength?: boolean; } } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 6f4f5624e1..5fe6332350 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for MongoDB v2.1 -// Project: https://github.com/mongodb/node-mongodb-native/tree/2.1 +// Type definitions for MongoDB v2.2 +// Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ +// Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ /// /// @@ -35,6 +35,7 @@ export interface MongoCallback { export class MongoError extends Error { constructor(message: string); static create(options: Object): MongoError; + code?: number; } //http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html#.connect @@ -303,7 +304,7 @@ export interface DbCollectionOptions { readConcern?: { level: Object }; } -//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex +//http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createIndex export interface IndexOptions { // The write concern. w?: number | string; @@ -331,6 +332,8 @@ export interface IndexOptions { expireAfterSeconds?: number; // Override the auto generated index name (useful if the resulting name is larger than 128 bytes) name?: string; + // Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + partialFilterExpression?: any; } // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html @@ -632,7 +635,7 @@ export interface CollectionAggregationOptions { allowDiskUse?: boolean; // specifies a cumulative time limit in milliseconds for processing operations // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - maxTimeMS?: boolean; + maxTimeMS?: number; // Allow driver to bypass schema validation in MongoDB 3.2 or higher. bypassDocumentValidation?: boolean; } diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index cba7f9a212..bf3f3e653f 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -24,6 +24,8 @@ MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err: mongodb.Mong collection.stats(function(err: mongodb.MongoError, stats: any) { console.log(stats.count + " documents"); }); + + collection.createIndex({}, {partialFilterExpression: {rating: {$exists: 1}}}) }); { diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index cb20b294d2..5a2a0abfe1 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1065,7 +1065,7 @@ declare module "mongoose" { * @param pathsToValidate only validate the given paths * @returns MongooseError if there are errors during validation, or undefined if there is no error. */ - validateSync(pathsToValidate: string | string[]): Error; + validateSync(pathsToValidate?: string | string[]): Error; /** Hash containing current validation errors. */ errors: Object; diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 5f013e33a1..390f487444 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for mssql 3.3 +// Type definitions for mssql 4.0.1 // Project: https://www.npmjs.com/package/mssql -// Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson , Jørgen Elgaard Larsen +// Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson , Jørgen Elgaard Larsen , Peter Keuter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,7 +8,7 @@ import events = require('events'); export interface ISqlType { - type: ISqlTypeFactory; + type: ISqlTypeFactory; } export interface ISqlTypeWithNoParams extends ISqlType { type: ISqlTypeFactoryWithNoParams } export interface ISqlTypeWithLength extends ISqlType { type: ISqlTypeFactoryWithLength; length: number } @@ -97,7 +97,6 @@ export declare var MAX: number; export declare var fix: boolean; export declare var Promise: any; - interface IMap extends Array<{ js: any, sql: any }> { register(jstype: any, sql: any): void; } @@ -110,10 +109,19 @@ export interface IColumnMetadata { index: number; name: string; length: number; - type: ISqlType; + type: ISqlType; udt?: any; } } +export interface IResult { + recordsets: IRecordSet[]; + recordset: IRecordSet; + rowsAffected: number[], + output: { [key: string]: any }; +} +export interface IProcedureResult extends IResult { + returnValue: any; +} export interface IRecordSet extends Array { columns: IColumnMetadata; } @@ -162,15 +170,18 @@ export interface config { pool?: IPool; } -export declare class Connection extends events.EventEmitter { +export declare class ConnectionPool extends events.EventEmitter { public connected: boolean; public connecting: boolean; public driver: string; public constructor(config: config, callback?: (err?: any) => void); - public connect(): Promise; + public constructor(connectionString: string, callback?: (err?: any) => void); + public query(strings: TemplateStringsArray, ...interpolations: any[]): Promise>; + public connect(): Promise; public connect(callback: (err: any) => void): void; public close(): Promise; public close(callback: (err: any) => void): void; + public request(): Request; } export declare class ConnectionError implements Error { @@ -209,32 +220,29 @@ interface IRequestParameters { } export declare class Request extends events.EventEmitter { - public connection: Connection; public transaction: Transaction; public pstatement: PreparedStatement; public parameters: IRequestParameters; public verbose: boolean; - public multiple: boolean; public canceled: boolean; public stream: any; - public constructor(connection?: Connection); + public constructor(connection?: ConnectionPool); public constructor(transaction: Transaction); public constructor(preparedStatement: PreparedStatement); - public execute(procedure: string): Promise>; - public execute(procedure: string): Promise>; - public execute(procedure: string, callback: (err?: any, recordsets?: IRecordSet, returnValue?: any, rowsAffected?: number) => void): void; + public execute(procedure: string): Promise>; + public execute(procedure: string): Promise>; + public execute(procedure: string, callback: (err?: any, recordsets?: IProcedureResult, returnValue?: any) => void): void; public input(name: string, value: any): Request; public input(name: string, type: any, value: any): Request; public output(name: string, type: any, value?: any): Request; public pipe(stream: NodeJS.WritableStream): NodeJS.WritableStream; - public query(command: string): Promise>; - public query(command: string): Promise>; - public query(command: string, callback: (err?: Error, recordset?: IRecordSet, rowsAffected?: number) => void): void; - public query(command: string, callback: (err?: Error, recordset?: IRecordSet) => void): void; - public batch(batch: string): Promise>; - public batch(batch: string): Promise>; - public batch(batch: string, callback: (err?: Error, recordset?: IRecordSet) => void): void; - public batch(batch: string, callback: (err?: any, recordset?: IRecordSet) => void): void; + public query(command: string): Promise>; + public query(command: string): Promise>; + public query(command: string, callback: (err?: Error, recordset?: IResult) => void): void; + public batch(batch: string): Promise>; + public batch(batch: string): Promise>; + public batch(batch: string, callback: (err?: Error, recordset?: IResult) => void): void; + public batch(batch: string, callback: (err?: any, recordset?: IResult) => void): void; public bulk(table: Table): Promise; public bulk(table: Table, callback: (err: Error, rowCount: any) => void): void; public cancel(): void; @@ -248,9 +256,8 @@ export declare class RequestError implements Error { } export declare class Transaction extends events.EventEmitter { - public connection: Connection; public isolationLevel: IIsolationLevel; - public constructor(connection?: Connection); + public constructor(connection?: ConnectionPool); public begin(isolationLevel?: IIsolationLevel): Promise; public begin(isolationLevel?: IIsolationLevel, callback?: (err?: any) => void): void; public commit(): Promise; @@ -267,14 +274,12 @@ export declare class TransactionError implements Error { } export declare class PreparedStatement extends events.EventEmitter { - public connection: Connection; public transaction: Transaction; public prepared: boolean; public statement: string; public parameters: IRequestParameters; - public multiple: boolean; public stream: any; - public constructor(connection?: Connection); + public constructor(connection?: ConnectionPool); public input(name: string, type: ISqlType): PreparedStatement; public output(name: string, type: ISqlType): PreparedStatement; public prepare(statement?: string): Promise; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index 764f6da8e1..c5e4535e44 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -1,7 +1,7 @@ import sql = require('mssql'); interface Entity{ - value: number; + value: number; } var config: sql.config = { @@ -15,34 +15,41 @@ var config: sql.config = { } } -var connection: sql.Connection = new sql.Connection(config, function (err: any) { +var connectionStringTest: sql.ConnectionPool = new sql.ConnectionPool("connectionstring", (err) => { + if (err) { + return err; + } +}); + +var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (err: any) { if (err != null) { console.warn("Issue with connecting to SQL Server!"); } else { + connection.query`SELECT ${1} as value`.then(res => { }); var requestQuery = new sql.Request(connection); var getArticlesQuery = "SELECT * FROM TABLE"; - requestQuery.query(getArticlesQuery, function (err, recordSet) { + requestQuery.query(getArticlesQuery, function (err, result) { if (err) { console.error('Error happened calling Query: ' + err.name + " " + err.message); } // checking to see if the articles returned as at least one. - else if (recordSet.length > 0) { + else if (result.recordset.length > 0) { } }); getArticlesQuery = "SELECT 1 as value FROM TABLE"; - requestQuery.query(getArticlesQuery, function (err, recordSet) { + requestQuery.query(getArticlesQuery, function (err, result) { if (err) { console.error('Error happened calling Query: ' + err.name + " " + err.message); } // checking to see if the articles returned as at least one. - else if (recordSet.length > 0 && recordSet[0].value) { + else if (result.recordset.length > 0 && result.recordset[0].value) { } }); @@ -124,7 +131,7 @@ function test_table() { function test_promise_returns() { // Methods return a promises if the callback is omitted. - var connection: sql.Connection = new sql.Connection(config); + var connection: sql.ConnectionPool = new sql.ConnectionPool(config); connection.connect().then(() => { }); connection.close().then(() => { }); @@ -150,7 +157,7 @@ function test_promise_returns() { function test_request_constructor() { // Request can be constructed with a connection, preparedStatment, transaction or no arguments - var connection: sql.Connection = new sql.Connection(config); + var connection: sql.ConnectionPool = new sql.ConnectionPool(config); var preparedStatment = new sql.PreparedStatement(connection); var transaction = new sql.Transaction(connection); @@ -161,7 +168,7 @@ function test_request_constructor() { } function test_classes_extend_eventemitter() { - var connection: sql.Connection = new sql.Connection(config); + var connection: sql.ConnectionPool = new sql.ConnectionPool(config); var transaction = new sql.Transaction(); var request = new sql.Request(); var preparedStatment = new sql.PreparedStatement(); diff --git a/types/multer-gridfs-storage/index.d.ts b/types/multer-gridfs-storage/index.d.ts new file mode 100644 index 0000000000..752609b4e3 --- /dev/null +++ b/types/multer-gridfs-storage/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for multer-gridfs-storage 1.1 +// Project: https://github.com/devconcept/multer-gridfs-storage +// Definitions by: devconcept +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {EventEmitter} from 'events'; +import {Express} from 'express'; +import * as Multer from 'multer'; +import {Grid} from 'gridfs-stream'; + +type logConfig = 'file' | 'all'; + +interface StorageLog { + message: string; + extra: any; +} + +type NodeCb = (err: Error | null, value: T | null) => void; + +type ConfigFn = (req: Express.Request, file: Express.Multer.File, cb: T) => void; + +// TODO: PR and add this interface to the mongodb types +interface GridFile { + _id: any; + filename: string; + contentType: string; + length: number; + chunkSize: number; + uploadDate: Date; + aliases: any; + metadata: any; + md5: string; +} + +interface MulterGfsOptions { + filename?: ConfigFn>; + identifier?: ConfigFn>; + metadata?: ConfigFn>; + chunkSize?: number | ConfigFn>; + root?: string | ConfigFn>; + log?: boolean | NodeCb; + logLevel?: logConfig; +} + +declare class MulterGridfsStorage extends EventEmitter implements Multer.StorageEngine { + constructor(settings: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.GfsStorageOptions); + + _handleFile(req: Express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; + + _removeFile(req: Express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; +} + +declare namespace MulterGridfsStorage { + interface UrlStorageOptions extends MulterGfsOptions { + url: string; + } + + interface GfsStorageOptions extends MulterGfsOptions { + gfs: Promise | Grid; + } +} + +// Merge multer's file declaration with ours +declare global { + namespace Express { + namespace Multer { + interface File { + filename: string; + metadata: any; + id: any; + grid: GridFile; + size: number; + } + } + } +} + +export = MulterGridfsStorage; diff --git a/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts new file mode 100644 index 0000000000..229fd7877d --- /dev/null +++ b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts @@ -0,0 +1,43 @@ +import * as MulterGridfsStorage from 'multer-gridfs-storage'; +import {Grid} from "gridfs-stream"; + +// Exported interfaces +let opt1: MulterGridfsStorage.GfsStorageOptions; +let opt2: MulterGridfsStorage.UrlStorageOptions; + +// All options +let gfsCtr = new MulterGridfsStorage({ + gfs: new Grid(), + filename: (req, file, cb) => cb(null, ''), + chunkSize: (req, file, cb) => cb(null, 1), + identifier: (req, file, cb) => cb(null, ''), + metadata: (req, file, cb) => cb(new Error(), null), + logLevel: 'all', + root: (req, file, cb) => cb(null, 'unicorns') +}); + +let urlCtr = new MulterGridfsStorage({ + url: '', + filename: (req, file, cb) => cb(null, ''), + chunkSize: (req, file, cb) => cb(null, 1), + identifier: (req, file, cb) => cb(null, ''), + metadata: (req, file, cb) => cb(new Error(), {}), + logLevel: 'all', + root: (req, file, cb) => cb(null, '') +}); + +// Other properties are optional +let gfsOnly = new MulterGridfsStorage({ + gfs: new Grid() +}); + +let urlOnly = new MulterGridfsStorage({ + url: '' +}); + +function noop() { +} +// Extends event emitter +gfsCtr.on('connection', noop); +urlCtr.addListener('conection', noop); +gfsOnly.removeAllListeners('conection'); diff --git a/types/multer-gridfs-storage/tsconfig.json b/types/multer-gridfs-storage/tsconfig.json new file mode 100644 index 0000000000..46054115e0 --- /dev/null +++ b/types/multer-gridfs-storage/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multer-gridfs-storage-tests.ts" + ] +} diff --git a/types/multer-gridfs-storage/tslint.json b/types/multer-gridfs-storage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/multer-gridfs-storage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mysql/index.d.ts b/types/mysql/index.d.ts index 7660feb374..9212d59ef6 100644 --- a/types/mysql/index.d.ts +++ b/types/mysql/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for node-mysql // Project: https://github.com/felixge/node-mysql // Definitions by: William Johnston +// Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -497,6 +498,11 @@ interface IError extends Error { * Boolean, indicating if this error is terminal to the connection object. */ fatal: boolean; + + /** + * SQL of failed query + */ + sql?: string; } declare const enum FieldType { diff --git a/types/ndarray/index.d.ts b/types/ndarray/index.d.ts index 52d86ff0c8..f409e7fe74 100644 --- a/types/ndarray/index.d.ts +++ b/types/ndarray/index.d.ts @@ -1,34 +1,36 @@ -// Type definitions for ndarray v1.0.18 +// Type definitions for ndarray 1.0 // Project: https://github.com/scijs/ndarray // Definitions by: Giff Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type Data = Array | Int8Array | Int16Array | Int32Array | - Uint8Array | Uint16Array | Uint32Array | - Float32Array | Float64Array | Uint8ClampedArray; - -interface ndarray { - data: Data; - shape: number[]; - stride: number[]; - offset: number; - dtype: 'int8' | 'int16' | 'int32' | 'uint8' | 'uint16' |'uint32' | - 'float32' | 'float64' | 'array'| 'uint8_clamped' | 'buffer' | 'generic'; - size: number; - order: number[]; - dimension: number; - get(...args: number[]): number; - set(...args: number[]): number; - index(...args: number[]): number; - lo(...args: number[]): ndarray; - hi(...args: number[]): ndarray; - step(...args: number[]): ndarray; - transpose(...args: number[]): ndarray; - pick(...args: number[]): ndarray; -} - declare function ndarray( - data: Data, shape?: number[], stride?: number[], offset?: number + data: ndarray.Data, shape?: number[], stride?: number[], offset?: number ): ndarray; +interface ndarray { + data: ndarray.Data; + shape: number[]; + stride: number[]; + offset: number; + dtype: 'int8' | 'int16' | 'int32' | 'uint8' | 'uint16' | 'uint32' | + 'float32' | 'float64' | 'array' | 'uint8_clamped' | 'buffer' | 'generic'; + size: number; + order: number[]; + dimension: number; + get(...args: number[]): number; + set(...args: number[]): number; + index(...args: number[]): number; + lo(...args: number[]): ndarray; + hi(...args: number[]): ndarray; + step(...args: number[]): ndarray; + transpose(...args: number[]): ndarray; + pick(...args: number[]): ndarray; +} + +declare namespace ndarray { + type Data = number[] | Int8Array | Int16Array | Int32Array | + Uint8Array | Uint16Array | Uint32Array | + Float32Array | Float64Array | Uint8ClampedArray; +} + export = ndarray; diff --git a/types/ndarray/ndarray-tests.ts b/types/ndarray/ndarray-tests.ts index a72a9acad5..899f43efd5 100644 --- a/types/ndarray/ndarray-tests.ts +++ b/types/ndarray/ndarray-tests.ts @@ -1,5 +1,4 @@ - -import ndarray = require('ndarray'); +import * as ndarray from 'ndarray'; const data = new Int32Array(2 * 2 * 2 + 10); const a = ndarray(data, [2, 2, 2], [1, 2, 4], 5); diff --git a/types/ndarray/tslint.json b/types/ndarray/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/ndarray/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/nedb/index.d.ts b/types/nedb/index.d.ts index d85016493e..15a2fd4e83 100644 --- a/types/nedb/index.d.ts +++ b/types/nedb/index.d.ts @@ -60,7 +60,7 @@ declare class Nedb { * If one update violates a constraint, all changes are rolled back */ updateIndexes(oldDoc: T, newDoc: T): void; - updateIndexes(updates: Array<{oldDoc: T; newDoc: T}>): void; + updateIndexes(updates: Array<{ oldDoc: T; newDoc: T }>): void; /** * Return the list of candidates for a given query diff --git a/types/nedb/nedb-tests.ts b/types/nedb/nedb-tests.ts index 9b5527051c..47af1b137f 100644 --- a/types/nedb/nedb-tests.ts +++ b/types/nedb/nedb-tests.ts @@ -54,7 +54,7 @@ class BaseCollection { findByID(id: string): Promise { return new Promise((resolve, reject) => { - this.dataStore.findOne({_id: id}, (err: Error, doc: T) => { + this.dataStore.findOne({ _id: id }, (err: Error, doc: T) => { if (err) { reject(err); } else { @@ -102,7 +102,7 @@ class BaseCollection { upsert(query: any, updateQuery: any): Promise { const a: Promise = new Promise((resolve, reject) => { - this.dataStore.update(query, updateQuery, {upsert: true}, (err: Error, numberOfUpdated: number, upsert: boolean) => { + this.dataStore.update(query, updateQuery, { upsert: true }, (err: Error, numberOfUpdated: number, upsert: boolean) => { if (err) { reject(err); } else { @@ -112,7 +112,7 @@ class BaseCollection { }); const b: Promise = new Promise((resolve, reject) => { - this.dataStore.update(query, updateQuery, {upsert: true}, (err: Error, numberOfUpdated: number, affectedDocs: any, upsert: boolean) => { + this.dataStore.update(query, updateQuery, { upsert: true }, (err: Error, numberOfUpdated: number, affectedDocs: any, upsert: boolean) => { if (err) { reject(err); } else { @@ -154,19 +154,19 @@ import Datastore = require('nedb'); let db = new Datastore(); // Type 2: Persistent datastore with manual loading -db = new Datastore({filename: 'path/to/datafile'}); +db = new Datastore({ filename: 'path/to/datafile' }); db.loadDatabase((err) => { // Callback is optional // Now commands will be executed }); // Type 3: Persistent datastore with automatic loading -db = new Datastore({filename: 'path/to/datafile', autoload: true}); +db = new Datastore({ filename: 'path/to/datafile', autoload: true }); // You can issue commands right away // Type 4: Persistent datastore for a Node Webkit app called 'nwtest' // For example on Linux, the datafile will be ~/.config/nwtest/nedb-data/something.db import path = require('path'); -db = new Datastore({filename: path.join(require('nw.gui').App.dataPath, 'something.db')}); +db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') }); // Of course you can create multiple datastores if you need several // collections. In this case it's usually a good idea to use autoload for all collections. @@ -179,14 +179,14 @@ dbContainer.users.loadDatabase(); dbContainer.robots.loadDatabase(); const doc: any = { - hello: 'world' - , n: 5 - , today: new Date() - , nedbIsAwesome: true - , notthere: null - , notToBeSaved: undefined // Will not be saved - , fruits: ['apple', 'orange', 'pear'] - , infos: {name: 'nedb'} + hello: 'world', + n: 5, + today: new Date(), + nedbIsAwesome: true, + notthere: null, + notToBeSaved: undefined, // Will not be saved + fruits: ['apple', 'orange', 'pear'], + infos: { name: 'nedb' } }; db.insert(doc, (err: Error, newDoc: any) => { // Callback is optional @@ -194,54 +194,54 @@ db.insert(doc, (err: Error, newDoc: any) => { // Callback is optional // newDoc has no key called notToBeSaved since its value was undefined }); -db.insert([{a: 5}, {a: 42}], (err: Error, newdocs: any[]) => { +db.insert([{ a: 5 }, { a: 42 }], (err: Error, newdocs: any[]) => { // Two documents were inserted in the database // newDocs is an array with these documents, augmented with their _id }); // If there is a unique constraint on field 'a', this will fail -db.insert([{a: 5}, {a: 42}, {a: 5}], (err: Error) => { +db.insert([{ a: 5 }, { a: 42 }, { a: 5 }], (err: Error) => { // err is a 'uniqueViolated' error // The database was not modified }); // Finding all planets in the solar system -db.find({system: 'solar'}, (err: Error, docs: any[]) => { +db.find({ system: 'solar' }, (err: Error, docs: any[]) => { // docs is an array containing documents Mars, Earth, Jupiter // If no document is found, docs is equal to [] }); // Finding all planets whose name contain the substring 'ar' using a regular expression -db.find({planet: /ar/}, (err: Error, docs: any[]) => { +db.find({ planet: /ar/ }, (err: Error, docs: any[]) => { // docs contains Mars and Earth }); // Finding all inhabited planets in the solar system -db.find({system: 'solar', inhabited: true}, (err: Error, docs: any[]) => { +db.find({ system: 'solar', inhabited: true }, (err: Error, docs: any[]) => { // docs is an array containing document Earth only }); // Use the dot-notation to match fields in subdocuments -db.find({"humans.genders": 2}, (err: Error, docs: any[]) => { +db.find({ "humans.genders": 2 }, (err: Error, docs: any[]) => { // docs contains Earth }); // Use the dot-notation to navigate arrays of subdocuments -db.find({"completeData.planets.name": "Mars"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.name": "Mars" }, (err: Error, docs: any[]) => { // docs contains document 5 }); -db.find({"completeData.planets.name": "Jupiter"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.name": "Jupiter" }, (err: Error, docs: any[]) => { // docs is empty }); -db.find({"completeData.planets.0.name": "Earth"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.0.name": "Earth" }, (err: Error, docs: any[]) => { // docs contains document 5 // If we had tested against "Mars" docs would be empty because we are matching against a specific array element }); // You can also deep-compare objects. Don't confuse this with dot-notation! -db.find({humans: {genders: 2}}, (err: Error, docs: any[]) => { +db.find({ humans: { genders: 2 } }, (err: Error, docs: any[]) => { // docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true } }); @@ -250,66 +250,66 @@ db.find({}, (err: Error, docs: any[]) => { }); // The same rules apply when you want to only find one document -db.findOne({_id: 'id1'}, (err: Error, doc: any) => { +db.findOne({ _id: 'id1' }, (err: Error, doc: any) => { // doc is the document Mars // If no document is found, doc is null }); // $lt, $lte, $gt and $gte work on numbers and strings -db.find({"humans.genders": {$gt: 5}}, (err: Error, docs: any[]) => { +db.find({ "humans.genders": { $gt: 5 } }, (err: Error, docs: any[]) => { // docs contains Omicron Persei 8, whose humans have more than 5 genders (7). }); // When used with strings, lexicographical order is used -db.find({planet: {$gt: 'Mercury'}}, (err: Error, docs: any[]) => { +db.find({ planet: { $gt: 'Mercury' } }, (err: Error, docs: any[]) => { // docs contains Omicron Persei 8 }); // Using $in. $nin is used in the same way -db.find({planet: {$in: ['Earth', 'Jupiter']}}, (err: Error, docs: any[]) => { +db.find({ planet: { $in: ['Earth', 'Jupiter'] } }, (err: Error, docs: any[]) => { // docs contains Earth and Jupiter }); // Using $exists -db.find({satellites: {$exists: true}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $exists: true } }, (err: Error, docs: any[]) => { // docs contains only Mars }); // Using $regex with another operator -db.find({planet: {$regex: /ar/, $nin: ['Jupiter', 'Earth']}}, (err: Error, docs: any[]) => { +db.find({ planet: { $regex: /ar/, $nin: ['Jupiter', 'Earth'] } }, (err: Error, docs: any[]) => { // docs only contains Mars because Earth was excluded from the match by $nin }); // Using an array-specific comparison function // Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error -db.find({satellites: {$size: 2}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $size: 2 } }, (err: Error, docs: any[]) => { // docs contains Mars }); -db.find({satellites: {$size: 1}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $size: 1 } }, (err: Error, docs: any[]) => { // docs is empty }); // If a document's field is an array, matching it means matching any element of the array -db.find({satellites: 'Phobos'}, (err: Error, docs: any[]) => { +db.find({ satellites: 'Phobos' }, (err: Error, docs: any[]) => { // docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' } }); // This also works for queries that use comparison operators -db.find({satellites: {$lt: 'Amos'}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $lt: 'Amos' } }, (err: Error, docs: any[]) => { // docs is empty since Phobos and Deimos are after Amos in lexicographical order }); // This also works with the $in and $nin operator -db.find({satellites: {$in: ['Moon', 'Deimos']}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $in: ['Moon', 'Deimos'] } }, (err: Error, docs: any[]) => { // docs contains Mars (the Earth document is not complete!) }); -db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}]}, (err: Error, docs: any[]) => { +db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }] }, (err: Error, docs: any[]) => { // docs contains Earth and Mars }); -db.find({$not: {planet: 'Earth'}}, (err: Error, docs: any[]) => { +db.find({ $not: { planet: 'Earth' } }, (err: Error, docs: any[]) => { // docs contains Mars, Jupiter, Omicron Persei 8 }); @@ -322,53 +322,53 @@ db.find({ }); // You can mix normal queries, comparison queries and logical operators -db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}], inhabited: true}, (err: Error, docs: any[]) => { +db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }], inhabited: true }, (err: Error, docs: any[]) => { // docs contains Earth }); // No query used means all results are returned (before the Cursor modifiers) -db.find({}).sort({planet: 1}).skip(1).limit(2).exec((err: Error, docs: any[]) => { +db.find({}).sort({ planet: 1 }).skip(1).limit(2).exec((err: Error, docs: any[]) => { // docs is [doc3, doc1] }); // You can sort in reverse order like this -db.find({system: 'solar'}).sort({planet: -1}).exec((err: Error, docs: any[]) => { +db.find({ system: 'solar' }).sort({ planet: -1 }).exec((err: Error, docs: any[]) => { // docs is [doc1, doc3, doc2] }); // You can sort on one field, then another, and so on like this: -db.find({}).sort({firstField: 1, secondField: -1}); +db.find({}).sort({ firstField: 1, secondField: -1 }); // Same database as above // Keeping only the given fields -db.find({planet: 'Mars'}, {planet: 1, system: 1}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 1, system: 1 }, (err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }] }); // Keeping only the given fields but removing _id -db.find({planet: 'Mars'}, {planet: 1, system: 1, _id: 0}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 1, system: 1, _id: 0 }, (err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar' }] }); // Omitting only the given fields and removing _id -db.find({planet: 'Mars'}, {planet: 0, system: 0, _id: 0}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 0, system: 0, _id: 0 }, (err: Error, docs: any[]) => { // docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }] }); // Failure: using both modes at the same time -db.find({planet: 'Mars'}, {planet: 0, system: 1}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 0, system: 1 }, (err: Error, docs: any[]) => { // err is the error message, docs is undefined }); // You can also use it in a Cursor way but this syntax is not compatible with MongoDB // If upstream compatibility is important don't use this method -db.find({planet: 'Mars'}).projection({planet: 1, system: 1}).exec((err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }).projection({ planet: 1, system: 1 }).exec((err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }] }); // Count all planets in the solar system -db.count({system: 'solar'}, (err: Error, count: number) => { +db.count({ system: 'solar' }, (err: Error, count: number) => { // count equals to 3 }); @@ -384,7 +384,7 @@ db.count({}, (err: Error, count: number) => { // { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true } // Replace a document by another -db.update({planet: 'Jupiter'}, {planet: 'Pluton'}, {}, (err: Error, numReplaced: number) => { +db.update({ planet: 'Jupiter' }, { planet: 'Pluton' }, {}, (err: Error, numReplaced: number) => { // numReplaced = 1 // The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' } // Note that the _id is kept unchanged, and the document has been replaced @@ -392,19 +392,19 @@ db.update({planet: 'Jupiter'}, {planet: 'Pluton'}, {}, (err: Error, numReplaced: }); // Set an existing field's value -db.update({system: 'solar'}, {$set: {system: 'solar system'}}, {multi: true}, (err: Error, numReplaced: number) => { +db.update({ system: 'solar' }, { $set: { system: 'solar system' } }, { multi: true }, (err: Error, numReplaced: number) => { // numReplaced = 3 // Field 'system' on Mars, Earth, Jupiter now has value 'solar system' }); // Setting the value of a non-existing field in a subdocument by using the dot-notation -db.update({planet: 'Mars'}, {$set: {"data.satellites": 2, "data.red": true}}, {}, () => { +db.update({ planet: 'Mars' }, { $set: { "data.satellites": 2, "data.red": true } }, {}, () => { // Mars document now is { _id: 'id1', system: 'solar', inhabited: false // , data: { satellites: 2, red: true } // } // Not that to set fields in subdocuments, you HAVE to use dot-notation // Using object-notation will just replace the top-level field - db.update({planet: 'Mars'}, {$set: {data: {satellites: 3}}}, {}, () => { + db.update({ planet: 'Mars' }, { $set: { data: { satellites: 3 } } }, {}, () => { // Mars document now is { _id: 'id1', system: 'solar', inhabited: false // , data: { satellites: 3 } // } @@ -413,23 +413,23 @@ db.update({planet: 'Mars'}, {$set: {"data.satellites": 2, "data.red": true}}, {} }); // Deleting a field -db.update({planet: 'Mars'}, {$unset: {planet: true}}, {}, () => { +db.update({ planet: 'Mars' }, { $unset: { planet: true } }, {}, () => { // Now the document for Mars doesn't contain the planet field // You can unset nested fields with the dot notation of course }); // Upserting a document -db.update({planet: 'Pluton'}, { +db.update({ planet: 'Pluton' }, { planet: 'Pluton', inhabited: false -}, {upsert: true}, (err: Error, numReplaced: number, upsert: boolean) => { +}, { upsert: true }, (err: Error, numReplaced: number, upsert: boolean) => { // numReplaced = 1, upsert = { _id: 'id5', planet: 'Pluton', inhabited: false } // A new document { _id: 'id5', planet: 'Pluton', inhabited: false } has been added to the collection }); // If you upsert with a modifier, the upserted doc is the query modified by the modifier // This is simpler than it sounds :) -db.update({planet: 'Pluton'}, {$inc: {distance: 38}}, {upsert: true}, () => { +db.update({ planet: 'Pluton' }, { $inc: { distance: 38 } }, { upsert: true }, () => { // A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection }); @@ -437,12 +437,12 @@ db.update({planet: 'Pluton'}, {$inc: {distance: 38}}, {upsert: true}, () => { // let's see how we can modify the array field atomically // $push inserts new elements at the end of the array -db.update({_id: 'id6'}, {$push: {fruits: 'banana'}}, {}, () => { +db.update({ _id: 'id6' }, { $push: { fruits: 'banana' } }, {}, () => { // Now the fruits array is ['apple', 'orange', 'pear', 'banana'] }); // $pop removes an element from the end (if used with 1) or the front (if used with -1) of the array -db.update({_id: 'id6'}, {$pop: {fruits: 1}}, {}, () => { +db.update({ _id: 'id6' }, { $pop: { fruits: 1 } }, {}, () => { // Now the fruits array is ['apple', 'orange'] // With { $pop: { fruits: -1 } }, it would have been ['orange', 'pear'] }); @@ -450,22 +450,22 @@ db.update({_id: 'id6'}, {$pop: {fruits: 1}}, {}, () => { // $addToSet adds an element to an array only if it isn't already in it // Equality is deep-checked (i.e. $addToSet will not insert an object in an array already containing the same object) // Note that it doesn't check whether the array contained duplicates before or not -db.update({_id: 'id6'}, {$addToSet: {fruits: 'apple'}}, {}, () => { +db.update({ _id: 'id6' }, { $addToSet: { fruits: 'apple' } }, {}, () => { // The fruits array didn't change // If we had used a fruit not in the array, e.g. 'banana', it would have been added to the array }); // $pull removes all values matching a value or even any NeDB query from the array -db.update({_id: 'id6'}, {$pull: {fruits: 'apple'}}, {}, () => { +db.update({ _id: 'id6' }, { $pull: { fruits: 'apple' } }, {}, () => { // Now the fruits array is ['orange', 'pear'] }); -db.update({_id: 'id6'}, {$pull: {fruits: {$in: ['apple', 'pear']}}}, {}, () => { +db.update({ _id: 'id6' }, { $pull: { fruits: { $in: ['apple', 'pear'] } } }, {}, () => { // Now the fruits array is ['orange'] }); // $each can be used to $push or $addToSet multiple values at once // This example works the same way with $addToSet -db.update({_id: 'id6'}, {$push: {fruits: {$each: ['banana', 'orange']}}}, {}, () => { +db.update({ _id: 'id6' }, { $push: { fruits: { $each: ['banana', 'orange'] } } }, {}, () => { // Now the fruits array is ['apple', 'orange', 'pear', 'banana', 'orange'] }); @@ -477,32 +477,32 @@ db.update({_id: 'id6'}, {$push: {fruits: {$each: ['banana', 'orange']}}}, {}, () // Remove one document from the collection // options set to {} since the default for multi is false -db.remove({_id: 'id2'}, {}, (err: Error, numRemoved: number) => { +db.remove({ _id: 'id2' }, {}, (err: Error, numRemoved: number) => { // numRemoved = 1 }); // Remove multiple documents -db.remove({system: 'solar'}, {multi: true}, (err: Error, numRemoved: number) => { +db.remove({ system: 'solar' }, { multi: true }, (err: Error, numRemoved: number) => { // numRemoved = 3 // All planets from the solar system were removed }); -db.ensureIndex({fieldName: 'somefield'}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield' }, (err: Error) => { // If there was an error, err is not null }); // Using a unique constraint with the index -db.ensureIndex({fieldName: 'somefield', unique: true}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield', unique: true }, (err: Error) => { }); // Using a sparse unique index -db.ensureIndex({fieldName: 'somefield', unique: true, sparse: true}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield', unique: true, sparse: true }, (err: Error) => { }); // Format of the error message when the unique constraint is not met -db.insert({somefield: 'nedb'}, (err: Error) => { +db.insert({ somefield: 'nedb' }, (err: Error) => { // err is null - db.insert({somefield: 'nedb'}, (err: Error) => { + db.insert({ somefield: 'nedb' }, (err: Error) => { // err is { errorType: 'uniqueViolated' // , key: 'name' // , message: 'Unique constraint violated for key name' } diff --git a/types/nes/client.d.ts b/types/nes/client.d.ts new file mode 100644 index 0000000000..8314894683 --- /dev/null +++ b/types/nes/client.d.ts @@ -0,0 +1,54 @@ +// Type definitions for nes 6.4.2 +// Project: https://github.com/hapijs/nes +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Client { + constructor(url: string, options?: Client.ClientOptions); + onError: (err: any) => void; + onConnect: () => void; + onDisconnect: () => void; + onUpdate: (message: any) => void; + connect(options: Client.ClientConnectOptions, callback: (err?: any) => void): void; + connect(callback: (err?: any) => void): void; + disconnect(): void; + id: any; // can be `null | number` but also the "socket" value from websocket message data. + request(options: string | Client.ClientRequestOptions, callback: (err: any, payload: any, statusCode?: number, headers?: Object) => void): void; + message(message: any, callback: (err: any, message: any) => void): void; + subscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; + unsubscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; + subscriptions(): string[]; + overrideReconnectionAuth(auth: any): void; +} + +declare namespace Client { + interface Handler { + (message: any, flags: Client.ClientSubscribeFlags): void; + } + + interface ClientOptions { + ws?: any; + timeout?: number | boolean; + } + + interface ClientConnectOptions { + auth?: any; + delay?: number; + maxDelay?: number; + retries?: number; + timeout?: number; + } + + interface ClientRequestOptions { + path: string; + method?: string; + headers?: Object; + payload?: any; + } + + interface ClientSubscribeFlags { + revoked?: boolean; + } +} + +export = Client; diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index 6ebc9ee1c0..87e428bc29 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -3,38 +3,58 @@ // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + * + * + * Removal of Nes.Server. No longer need to cast to Nes.Server as Hapi.Server + * has been modified directly. + * Removal of Nes.Request. Same reason as Nes.Server + * Move Nes.Socket from class to just an interface as it is not mentioned + * publically in docs. Perhaps this should be included though? Add + * failing test demonstrating use if so. + */ -declare module 'nes' { - import Hapi = require('hapi'); +import * as Hapi from 'hapi'; +import NesClient = require('nes/client'); - export interface SocketAuthObject { +declare module 'hapi' { + interface Server { + broadcast(message: any, options?: nes.ServerBroadcastOptions): void; + subscription(path: string, options?: nes.ServerSubscriptionOptions): void; + publish(path: string, message: any, options?: nes.ServerPublishOptions): void; + eachSocket(each: (socket: nes.Socket) => void, options?: nes.ServerEachSocketOptions): void; + } + + interface Request { + socket: nes.Socket; + } +} + +declare module nes { + interface SocketAuthObject { isAuthenticated: boolean; credentials: any; artifacts: any; } - export class Socket { - id: any; - app: Object; - auth: SocketAuthObject; - disconect(callback?: () => void): void; - send(message: any, callback?: (err?: any) => void): void; - publish(path: string, message: any, callback?: (err?: any) => void): void; - revoke(path: string, message: any, callback?: (err?: any) => void): void; - } - - export interface ServerBroadcastOptions { + interface ServerBroadcastOptions { user: any } - export interface ServerSubscriptionOptionsFilterOptions { + interface ServerSubscriptionOptionsFilterOptions { socket: Socket; credentials?: any; params?: any; } - export interface ServerSubscriptionOptionsAuthOptions { + interface ServerSubscriptionOptionsAuthOptions { mode?: 'required' | 'optional'; scope?: string | string[]; entity?: 'user' | 'app' | 'any'; @@ -49,82 +69,66 @@ declare module 'nes' { export type ServerOnUnSubscribeWithoutParams = (socket: Socket, path: string, next: () => void) => void; export type ServerOnUnSubscribe = ServerOnUnSubscribeWithParams | ServerOnUnSubscribeWithoutParams; - export interface ServerSubscriptionOptions { - filter?: (path: string, message: any, options: ServerSubscriptionOptionsFilterOptions, next: (isMatch: boolean, override: any) => void) => void; + interface ServerSubscriptionOptions { + filter?: (path: string, message: any, options: ServerSubscriptionOptionsFilterOptions, next: (isMatch: boolean, override?: any) => void) => void; auth?: boolean | ServerSubscriptionOptionsAuthOptions; onSubscribe?: ServerOnSubscribe; onUnsubscribe?: ServerOnUnSubscribe; } - export interface ServerPublishOptions { + interface ServerPublishOptions { internal?: any; user?: any; } - export interface ServerEachSocketOptions { + interface ServerEachSocketOptions { subscription?: string; user?: any; } - export class Server extends Hapi.Server { - broadcast(message: any, options?: ServerBroadcastOptions): void; - subscription(path: string, options?: ServerSubscriptionOptions): void; - publish(path: string, message: any, options?: ServerPublishOptions): void; - eachSocket(each: (socket: Socket) => void, options?: ServerEachSocketOptions): void; + interface Socket { + id: string; + app: Object; + auth: nes.SocketAuthObject; + disconect(callback?: () => void): void; + send(message: any, callback?: (err?: any) => void): void; + publish(path: string, message: any, callback?: (err?: any) => void): void; + revoke(path: string, message: any, callback?: (err?: any) => void): void; } - export class Request extends Hapi.Request { - socket: Socket; - } + /** + * TODO (if possible) use a drier, more robust way of doing this that + * allows for: + * * the export to have be of type Hapi.PluginFunction whilst + * * also exposing the Client type + * * exporting the NesClient as the Client class without having to + * duplicate the constructor definition + * * and all the type exports from the NesClient namespace (Handler, + * ClientOptions, ClientConnectOptions, ClientRequestOptions, + * ClientSubscribeFlags) + */ - export interface ClientOptions { - ws?: any; - timeout?: number | boolean; - } + interface Client extends NesClient {} - export interface ClientConnectOptions { - auth?: any; - delay?: number; - maxDelay?: number; - retries?: number; - timeout?: number; - } + interface Handler extends NesClient.Handler {} - export interface ClientRequestOptions { - path: string; - method?: string; - headers?: Object; - payload?: any; - } + interface ClientOptions extends NesClient.ClientOptions {} - export interface ClientSubscribeFlags { - revoked?: boolean; - } + interface ClientConnectOptions extends NesClient.ClientConnectOptions {} - export class Client { - constructor(url: string, options?: ClientOptions); - onError: (err: any) => void; - onConnect: () => void; - onDisconnect: () => void; - onUpdate: (message: any) => void; - connect(options: ClientConnectOptions, callback: (err?: any) => void): void; - connect(callback: (err?: any) => void): void; - disconnect(): void; - id: any; - request(options: string | ClientRequestOptions, callback: (err: any, payload: any, statusCode?: number, headers?: Object) => void): void; - message(message: any, callback: (err: any, message: any) => void): void; - subscribe(path: string, handler: (message: any, flags: ClientSubscribeFlags) => void, callback: (err?: any) => void): void; - unsubscribe(path: string, handler: (message: any, flags: ClientSubscribeFlags) => void, callback: (err?: any) => void): void; - subscriptions(): string[]; - overrideReconnectionAuth(auth: any): void; - } + interface ClientRequestOptions extends NesClient.ClientRequestOptions {} + + interface ClientSubscribeFlags extends NesClient.ClientSubscribeFlags {} } -declare module 'nes/client' { - export { - Client, - ClientConnectOptions, - ClientRequestOptions, - ClientSubscribeFlags - } from 'nes'; +interface NesClassExports { + Client: { + new(url: string, options?: NesClient.ClientOptions): NesClient; + }; } + +interface NesAllExports extends NesClassExports, Hapi.PluginFunction<{}> {} + +declare var nes: NesAllExports; + +export = nes; diff --git a/types/nes/test/broadcast-client.ts b/types/nes/test/broadcast-client.ts new file mode 100644 index 0000000000..4c94b8c575 --- /dev/null +++ b/types/nes/test/broadcast-client.ts @@ -0,0 +1,25 @@ +// from https://github.com/hapijs/nes#broadcast + +import Nes = require('nes'); + +var client = new Nes.Client('ws://localhost'); +client.connect(function (err) { + + client.onUpdate = function (update) { + + // update -> 'welcome!' + }; +}); + +// Added in addition to nes doc example code + +import NesClient = require('nes/client'); + +var client = new NesClient('ws://localhost'); +client.connect(function (err) { + + client.onUpdate = function (update) { + + // update -> 'welcome!' + }; +}); diff --git a/types/nes/test/broadcast-server.ts b/types/nes/test/broadcast-server.ts new file mode 100644 index 0000000000..dcfcb3400e --- /dev/null +++ b/types/nes/test/broadcast-server.ts @@ -0,0 +1,15 @@ +// from https://github.com/hapijs/nes#broadcast + +import Hapi = require('hapi'); +import Nes = require('nes'); + +var server = new Hapi.Server(); +server.connection(); + +server.register(Nes, function (err) { + + server.start(function (err) { + + server.broadcast('welcome!'); + }); +}); diff --git a/types/nes/test/client-require.ts b/types/nes/test/client-require.ts new file mode 100644 index 0000000000..f5a07ea1d3 --- /dev/null +++ b/types/nes/test/client-require.ts @@ -0,0 +1,12 @@ +// from https://github.com/hapijs/nes/#browser-client +// When you require('nes') it loads the full module and adds a lot of extra code +// that is not needed for the browser. The browser will only need the nes client. +// If you are using CommonJS you can load the client with require('nes/client'). + +import Client = require('nes/client'); + +var options: Client.ClientConnectOptions = { + delay: 3 +} + +var client: Client = new Client('ws://localhost', options); diff --git a/types/nes/nes-tests.ts b/types/nes/test/nes-tests.ts similarity index 72% rename from types/nes/nes-tests.ts rename to types/nes/test/nes-tests.ts index effe4e6c94..90afe68f3e 100644 --- a/types/nes/nes-tests.ts +++ b/types/nes/test/nes-tests.ts @@ -1,22 +1,24 @@ import Hapi = require('hapi'); import Nes = require('nes'); -let server: Hapi.Server = new Hapi.Server(); +var server: Hapi.Server = new Hapi.Server(); server.connection({port: 8080}); -server.register(Nes, (regErr: any) => { +server.register(Nes, (regErr) => { if(regErr) { console.log('register err'); console.log(regErr); } else { - let wsServer: Nes.Server = server as Nes.Server; + // No longer need to cast to Nes.Server as Hapi.Server has been modified directly. + // let wsServer: Nes.Server = server as Nes.Server; + let wsServer: Hapi.Server = server; wsServer.subscription('/item/{id}'); wsServer.route( { method: 'GET', path: '/test', config: { - handler: (request: Hapi.Request, reply: Hapi.IReply) => { - reply({test: 'passes'}); + handler: (request, reply) => { + reply({test: 'passes ' + request.socket.id}); } } }); @@ -34,14 +36,16 @@ server.register(Nes, (regErr: any) => { } }); -let wsClient: Nes.Client = new Nes.Client('ws://localhost:8080'); +let options: Nes.ClientConnectOptions = {delay: 3}; + +let wsClient: Nes.Client = new Nes.Client('ws://localhost:8080', options); wsClient.connect((err: any) => { if(err) { console.log('start err'); console.log(err); } else { wsClient.subscribe('/item/5', (update) => { - wsClient.request('/test', (reqErr: any, payload: any, statusCode: number) => { + wsClient.request('/test', (reqErr, payload, statusCode) => { if(reqErr) { console.log('request err'); console.log(reqErr); diff --git a/types/nes/test/route-authentication-client.ts b/types/nes/test/route-authentication-client.ts new file mode 100644 index 0000000000..fe57eb8d56 --- /dev/null +++ b/types/nes/test/route-authentication-client.ts @@ -0,0 +1,25 @@ +// from https://github.com/hapijs/nes#route-authentication + +import Nes = require('nes'); + +var client = new Nes.Client('ws://localhost'); +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { + + client.request('hello', function (err, payload) { // Can also request '/h' + + // payload -> 'Hello John Doe' + }); +}); + +// Added in addition to nes doc example code + +import NesClient = require('nes/client'); + +var client = new NesClient('ws://localhost'); +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { + + client.request('hello', function (err, payload) { // Can also request '/h' + + // payload -> 'Hello John Doe' + }); +}); diff --git a/types/nes/test/route-authentication-server.ts b/types/nes/test/route-authentication-server.ts new file mode 100644 index 0000000000..5b4634d77d --- /dev/null +++ b/types/nes/test/route-authentication-server.ts @@ -0,0 +1,61 @@ +// from https://github.com/hapijs/nes#route-authentication + +import Hapi = require('hapi'); +import Basic = require('hapi-auth-basic'); +import Bcrypt = require('bcrypt'); +import Nes = require('nes'); + +var server = new Hapi.Server(); +server.connection(); + +server.register([Basic, Nes], function (err) { + + // Set up HTTP Basic authentication + + interface User { + username: string; + password: string; + name: string; + id: string; + } + + var users: {[index: string]: User} = { + john: { + username: 'john', + password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' + name: 'John Doe', + id: '2133d32a' + } + }; + + var validate: Basic.ValidateFunc = function (request, username, password, callback) { + + var user = users[username]; + if (!user) { + return callback(null, false); + } + + Bcrypt.compare(password, user.password, function (err, isValid) { + + callback(err, isValid, { id: user.id, name: user.name }); + }); + }; + + server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + + // Configure route with authentication + + server.route({ + method: 'GET', + path: '/h', + config: { + id: 'hello', + handler: function (request, reply) { + + return reply('Hello ' + request.auth.credentials.name); + } + } + }); + + server.start(function (err) { /* ... */ }); +}); diff --git a/types/nes/test/route-invocation-client.ts b/types/nes/test/route-invocation-client.ts new file mode 100644 index 0000000000..7b144e3a9c --- /dev/null +++ b/types/nes/test/route-invocation-client.ts @@ -0,0 +1,25 @@ +// from https://github.com/hapijs/nes#route-invocation + +import Nes = require('nes'); + +var client = new Nes.Client('ws://localhost'); +client.connect(function (err) { + + client.request('hello', function (err, payload) { // Can also request '/h' + + // payload -> 'world!' + }); +}); + +// Added in addition to nes doc example code + +import NesClient = require('nes/client'); + +var client = new NesClient('ws://localhost'); +client.connect(function (err) { + + client.request('hello', function (err, payload) { // Can also request '/h' + + // payload -> 'world!' + }); +}); diff --git a/types/nes/test/route-invocation-server.ts b/types/nes/test/route-invocation-server.ts new file mode 100644 index 0000000000..c32780baa9 --- /dev/null +++ b/types/nes/test/route-invocation-server.ts @@ -0,0 +1,24 @@ +// from https://github.com/hapijs/nes#route-invocation + +import Hapi = require('hapi'); +import Nes = require('nes'); + +var server = new Hapi.Server(); +server.connection(); + +server.register(Nes, function (err) { + + server.route({ + method: 'GET', + path: '/h', + config: { + id: 'hello', + handler: function (request, reply) { + + return reply('world!'); + } + } + }); + + server.start(function (err) { /* ... */ }); +}); diff --git a/types/nes/test/subscription-filter-client.ts b/types/nes/test/subscription-filter-client.ts new file mode 100644 index 0000000000..3f8d3ffb8b --- /dev/null +++ b/types/nes/test/subscription-filter-client.ts @@ -0,0 +1,37 @@ +// from https://github.com/hapijs/nes#subscription-filter + +import Nes = require('nes'); + +var client = new Nes.Client('ws://localhost'); + +// Authenticate as 'john' + +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { + + var handler: Nes.Handler = function (err, update) { + + // First publish is not received (filtered due to updater key) + // update -> { id: 6, status: 'initial', updater: 'steve' } + }; + + client.subscribe('/items', handler, function (err) { }); +}); + +// Added in addition to nes doc example code + +import NesClient = require('nes/client'); + +var client = new NesClient('ws://localhost'); + +// Authenticate as 'john' + +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { + + var handler: NesClient.Handler = function (err, update) { + + // First publish is not received (filtered due to updater key) + // update -> { id: 6, status: 'initial', updater: 'steve' } + }; + + client.subscribe('/items', handler, function (err) { }); +}); diff --git a/types/nes/test/subscription-filter-server.ts b/types/nes/test/subscription-filter-server.ts new file mode 100644 index 0000000000..be2dda8d7f --- /dev/null +++ b/types/nes/test/subscription-filter-server.ts @@ -0,0 +1,60 @@ +// from https://github.com/hapijs/nes#subscription-filter + +import Hapi = require('hapi'); +import Basic = require('hapi-auth-basic'); +import Bcrypt = require('bcrypt'); +import Nes = require('nes'); + +var server = new Hapi.Server(); +server.connection(); + +server.register([Basic, Nes], function (err) { + + // Set up HTTP Basic authentication + + interface User { + username: string; + password: string; + name: string; + id: string; + } + + var users: {[index: string]: User} = { + john: { + username: 'john', + password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' + name: 'John Doe', + id: '2133d32a' + } + }; + + var validate: Basic.ValidateFunc = function (request, username, password, callback) { + + var user = users[username]; + if (!user) { + return callback(null, false); + } + + Bcrypt.compare(password, user.password, function (err, isValid) { + + callback(err, isValid, { id: user.id, name: user.name, username: user.username }); + }); + }; + + server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + + // Set up subscription + + server.subscription('/items', { + filter: function (path, message, options, next) { + + return next(message.updater !== options.credentials.username); + } + }); + + server.start(function (err) { + + server.publish('/items', { id: 5, status: 'complete', updater: 'john' }); + server.publish('/items', { id: 6, status: 'initial', updater: 'steve' }); + }); +}); diff --git a/types/nes/test/subscriptions-client.ts b/types/nes/test/subscriptions-client.ts new file mode 100644 index 0000000000..a9ac55fc6d --- /dev/null +++ b/types/nes/test/subscriptions-client.ts @@ -0,0 +1,31 @@ +// from https://github.com/hapijs/nes#subscriptions + +import Nes = require('nes'); + +var client = new Nes.Client('ws://localhost'); +client.connect(function (err) { + + var handler: Nes.Handler = function (update, flags) { + + // update -> { id: 5, status: 'complete' } + // Second publish is not received (doesn't match) + }; + + client.subscribe('/item/5', handler, function (err) { }); +}); + +// Added in addition to nes doc example code + +import NesClient = require('nes/client'); + +var client = new NesClient('ws://localhost'); +client.connect(function (err) { + + var handler: NesClient.Handler = function (update, flags) { + + // update -> { id: 5, status: 'complete' } + // Second publish is not received (doesn't match) + }; + + client.subscribe('/item/5', handler, function (err) { }); +}); diff --git a/types/nes/test/subscriptions-server.ts b/types/nes/test/subscriptions-server.ts new file mode 100644 index 0000000000..23212f21ea --- /dev/null +++ b/types/nes/test/subscriptions-server.ts @@ -0,0 +1,18 @@ +// from https://github.com/hapijs/nes#subscriptions + +import Hapi = require('hapi'); +import Nes = require('nes'); + +var server = new Hapi.Server(); +server.connection(); + +server.register(Nes, function (err) { + + server.subscription('/item/{id}'); + + server.start(function (err) { + + server.publish('/item/5', { id: 5, status: 'complete' }); + server.publish('/item/6', { id: 6, status: 'initial' }); + }); +}); diff --git a/types/nes/tsconfig.json b/types/nes/tsconfig.json index 74c7bfef19..cb28129b71 100644 --- a/types/nes/tsconfig.json +++ b/types/nes/tsconfig.json @@ -17,6 +17,18 @@ }, "files": [ "index.d.ts", - "nes-tests.ts" + "client.d.ts", + "test/client-require.ts", + "test/nes-tests.ts", + "test/broadcast-client.ts", + "test/broadcast-server.ts", + "test/route-authentication-client.ts", + "test/route-authentication-server.ts", + "test/route-invocation-client.ts", + "test/route-invocation-server.ts", + "test/subscription-filter-client.ts", + "test/subscription-filter-server.ts", + "test/subscriptions-client.ts", + "test/subscriptions-server.ts" ] } \ No newline at end of file diff --git a/types/ngstorage/index.d.ts b/types/ngstorage/index.d.ts index 15fb3c0481..83c740ff0e 100644 --- a/types/ngstorage/index.d.ts +++ b/types/ngstorage/index.d.ts @@ -1,23 +1,48 @@ -// Type definitions for ngstorage 0.3.11 +// Type definitions for ngstorage 0.3 // Project: https://github.com/gsklee/ngStorage // Definitions by: Jakub Pistek // Definitions: https://github.com/kubiq/DefinitelyTyped -declare module 'ngstorage' { +export namespace ngStorage { + interface StorageService { + /** + * @return true if the storage service is supported by the browser. + */ + $supported(): boolean; + + /** + * Adds default values to the store. + * Copies all properties of the default items to the store. + * If the store already has one of these properties it will skip it. + * + * @param items object holding the default values. + * @return the modified storage service. + */ + $default(items: T): StorageService & T; + + /** + * Removes all properties from the store. + * + * @param items optional object holding the default values to initialize the store after reset. + * @return the modified storage service. + */ + $reset(items?: T): StorageService & T; - interface IStorageService { - $default(items: {}): IStorageService; - $reset(items?: {}): IStorageService; $apply(): void; $sync(): void; - get(key: string): T; + + /** + * Access to the properties of the store. + */ + [key: string]: any; } - interface IStorageProvider extends angular.IServiceProvider { - - get(key: string): T; - set(key: string, value: T): T; + interface StorageProvider extends angular.IServiceProvider { + get(key: string): T | boolean; + set(key: string, value: T): T | boolean; + remove(key: string): void; + supported(): boolean; setKeyPrefix(prefix: string): void; setSerializer(serializer: (value: any) => string): void; setDeserializer(deserializer: (value: string) => any): void; diff --git a/types/ngstorage/ngstorage-tests.ts b/types/ngstorage/ngstorage-tests.ts index abddf19bb7..a69d905a55 100644 --- a/types/ngstorage/ngstorage-tests.ts +++ b/types/ngstorage/ngstorage-tests.ts @@ -1,78 +1,81 @@ -/// +import * as angular from "angular"; +import { ngStorage } from "ngstorage"; -import {IStorageService, IStorageProvider} from "ngstorage"; +let app: angular.IModule = angular.module('at', ['ngStorage']); -var app: any; -app.controller('LocalCtrl', function ($localStorage: IStorageService) { +app.controller('LocalCtrl', ($localStorage: ngStorage.StorageService) => { + if ($localStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $localStorage.$default({ + counter: 1 + }); - $localStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $localStorage.$reset({ - counter: 1 - }); - - $localStorage.$reset(); - - $localStorage.$apply(); - - $localStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.controller('SessionCtrl', function ($sessionStorage: IStorageService) { +app.controller('SessionCtrl', ($sessionStorage: ngStorage.StorageService) => { + if ($sessionStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $sessionStorage.$default({ + counter: 1 + }); - $sessionStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $sessionStorage.$reset({ - counter: 1 - }); - - $sessionStorage.$reset(); - - $sessionStorage.$apply(); - - $sessionStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.config(['$localStorageProvider', function ($localStorageProvider: IStorageProvider) { +app.config(($localStorageProvider: ngStorage.StorageProvider) => { + if ($localStorageProvider.supported()) { + $localStorageProvider.setKeyPrefix('NewPrefix'); + $localStorageProvider.set('MyKey', { counter: 'value' }); + $localStorageProvider.get('MyKey'); + $localStorageProvider.remove('MyKey'); - $localStorageProvider.setKeyPrefix('NewPrefix'); + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.get('MyKey'); + const myDeserializer = (value: string): any => { + return value; + }; - $localStorageProvider.set('MyKey', {counter: 'value'}); + $localStorageProvider.setSerializer(mySerializer); + $localStorageProvider.setDeserializer(myDeserializer); + } +}); - var mySerializer = function (value: any): string { - return value.toString(); - }; +app.config(($sessionStorageProvider: ngStorage.StorageProvider) => { + if ($sessionStorageProvider.supported()) { + $sessionStorageProvider.setKeyPrefix('NewPrefix'); + $sessionStorageProvider.set('MyKey', { counter: 'value' }); + $sessionStorageProvider.get('MyKey'); + $sessionStorageProvider.remove('MyKey'); - var myDeserializer = function (value: string): any { - return value; - }; + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.setSerializer(mySerializer); - $localStorageProvider.setDeserializer(myDeserializer); + const myDeserializer = (value: string): any => { + return value; + }; + + $sessionStorageProvider.setSerializer(mySerializer); + $sessionStorageProvider.setDeserializer(myDeserializer); + } +}); + +interface MyStore { + counter?: number; + foo?: string; } -]).config(['$sessionStorageProvider', function ($sessionStorageProvider: IStorageProvider) { - - $sessionStorageProvider.setKeyPrefix('NewPrefix'); - - $sessionStorageProvider.get('MyKey'); - - $sessionStorageProvider.set('MyKey', {counter: 'value'}); - - var mySerializer = function (value: any): string { - return value.toString(); - }; - - var myDeserializer = function (value: string): any { - return value; - }; - - $sessionStorageProvider.setSerializer(mySerializer); - $sessionStorageProvider.setDeserializer(myDeserializer); -} -]); diff --git a/types/ngstorage/tsconfig.json b/types/ngstorage/tsconfig.json index a3cdb4a204..fffe367328 100644 --- a/types/ngstorage/tsconfig.json +++ b/types/ngstorage/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/ngstorage/tslint.json b/types/ngstorage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ngstorage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node-ipc/node-ipc-tests.ts b/types/node-ipc/node-ipc-tests.ts index b6affa8f16..69a8ffa46e 100644 --- a/types/node-ipc/node-ipc-tests.ts +++ b/types/node-ipc/node-ipc-tests.ts @@ -57,7 +57,7 @@ ipc.of.world.on("socket.disconnected", (socket: Socket, id: string) => { id.toLo ipc.of.world.on("message", (data: any, data2: any) => { }); ipc.server.emit("event", [1, 2, 3]); const myBuffer = new Buffer(6).fill(0); -let socket: Socket = {} as any; +declare const socket: Socket; ipc.server.emit(socket, myBuffer); ipc.server.emit([10, 20, 30]); ipc.server.emit({ address: 'localhost', port: 8000 }, "message", { id: ipc.config.id, message: 'Goodbye' }); diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 7805819383..67f275c7b6 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Node.js v7.x // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions by: Microsoft TypeScript , DefinitelyTyped , Parambir Singh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -1091,18 +1091,25 @@ declare module "zlib" { export function createUnzip(options?: ZlibOptions): Unzip; export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflate(buf: Buffer | string, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gzip(buf: Buffer, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gunzip(buf: Buffer, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflate(buf: Buffer, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateRaw(buf: Buffer, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function unzip(buf: Buffer, options: ZlibOptions, callback: (error: Error, result: Buffer) => void): void; export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; export namespace constants { @@ -1886,23 +1893,110 @@ declare module "url" { } declare module "dns" { - export interface MxRecord { - exchange: string, - priority: number + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; } - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[][]) => void): string[][]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + export interface ResolveOptions { + ttl: boolean; + } + + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + export interface RecordWithTtl { + address: string; + ttl: number; + } + + export interface MxRecord { + priority: number; + exchange: string; + } + + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][]) => void): void; + + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; export function setServers(servers: string[]): void; //Error codes @@ -2122,7 +2216,7 @@ declare module "net" { prependOnceListener(event: "listening", listener: () => void): this; } export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; @@ -3650,23 +3744,23 @@ declare module "util" { export function log(string: string): void; export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; + export function isArray(object: any): object is any[]; + export function isRegExp(object: any): object is RegExp; + export function isDate(object: any): object is Date; + export function isError(object: any): object is Error; export function inherits(constructor: any, superConstructor: any): void; export function debuglog(key: string): (msg: string, ...param: any[]) => void; - export function isBoolean(object: any): boolean; - export function isBuffer(object: any): boolean; + export function isBoolean(object: any): object is boolean; + export function isBuffer(object: any): object is Buffer; export function isFunction(object: any): boolean; - export function isNull(object: any): boolean; - export function isNullOrUndefined(object: any): boolean; - export function isNumber(object: any): boolean; + export function isNull(object: any): object is null; + export function isNullOrUndefined(object: any): object is null | undefined; + export function isNumber(object: any): object is number; export function isObject(object: any): boolean; export function isPrimitive(object: any): boolean; - export function isString(object: any): boolean; - export function isSymbol(object: any): boolean; - export function isUndefined(object: any): boolean; + export function isString(object: any): object is string; + export function isSymbol(object: any): object is symbol; + export function isUndefined(object: any): object is undefined; export function deprecate(fn: Function, message: string): Function; } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 568d15d096..7cac17144e 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -25,6 +25,7 @@ import * as stream from "stream"; import * as timers from "timers"; import * as repl from "repl"; import * as v8 from "v8"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -533,19 +534,25 @@ const compressMe = new Buffer("some data"); const compressMeString = "compress me!"; zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +zlib.deflateRaw(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); +zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); zlib.unzip(compressMe, (err: Error, result: Buffer) => result); +zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); const unzipped: Buffer = zlib.unzipSync(compressMe); // Simplified constructors @@ -2127,6 +2134,98 @@ namespace repl_tests { } } +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve4("nodejs.org", {ttl: true}, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve4("nodejs.org", {ttl: ttl}, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve6("nodejs.org", {ttl: true}, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve6("nodejs.org", {ttl: ttl}, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 5914d22a4c..8cb1452030 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -20,4 +20,4 @@ "forceConsistentCasingInFileNames": true, "isolatedModules": true } -} \ No newline at end of file +} diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index f9d804c7eb..c74f8dcb0b 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1242,18 +1242,117 @@ declare module "url" { } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + export interface MxRecord { + priority: number; + exchange: string; + } + + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][]) => void): void; + + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; } declare module "net" { diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index d61693f1a6..5274116452 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -19,6 +19,7 @@ import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; import * as string_decoder from "string_decoder"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -968,3 +969,77 @@ namespace net_tests { net.createServer().listen(0).close().address(); } } + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); +} diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 6bac11b605..ebc2b516d6 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -358,10 +358,19 @@ declare namespace NodeJS { isTTY?: true; } + export interface WriteStream extends Socket { + columns?: number; + rows?: number; + } + export interface ReadStream extends Socket { + isRaw?: boolean; + setRawMode?(mode: boolean): void; + } + export interface Process extends EventEmitter { - stdout: Socket; - stderr: Socket; - stdin: Socket; + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; argv: string[]; argv0: string; execArgv: string[]; @@ -1798,23 +1807,91 @@ declare module "url" { } declare module "dns" { - export interface MxRecord { - exchange: string, - priority: number + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; } - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + export interface MxRecord { + priority: number; + exchange: string; + } + + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][]) => void): void; + + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; export function setServers(servers: string[]): void; //Error codes diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 0e03b1d94a..b2ca08898c 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -24,6 +24,7 @@ import * as string_decoder from "string_decoder"; import * as stream from "stream"; import * as timers from "timers"; import * as repl from "repl"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -2039,6 +2040,80 @@ namespace repl_tests { } } +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * diff --git a/types/nodemailer-smtp-transport/index.d.ts b/types/nodemailer-smtp-transport/index.d.ts index da3bd13f31..7f0f8d7cca 100644 --- a/types/nodemailer-smtp-transport/index.d.ts +++ b/types/nodemailer-smtp-transport/index.d.ts @@ -18,6 +18,30 @@ declare namespace smtpTransport { /** indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’ */ type?: any; + + /** is the registered client id of the application */ + clientId?: string; + + /** is the registered client secret of the application */ + clientSecret?: string; + + /** is an optional refresh token. If it is provided then Nodemailer tries to generate a new access token if existing one expires or fails */ + refreshToken?: string; + + /** is the access token for the user. Required only if refreshToken is not available and there is no token refresh callback specified */ + accessToken?: string; + + /** is an optional expiration time for the current accessToken */ + expires?: number; + + /** is an optional HTTP endpoint for requesting new access tokens. This value defaults to Gmail */ + accessUrl?: string; + + /** service client id, you can find it from the “client_id” field in the service key file */ + serviceClient?: string; + + /** is the private key contents, you can find it from the “private_key” field in the service key file */ + privateKey?: string; } export interface SmtpOptions { diff --git a/types/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts b/types/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts index 45b8a3a24d..ccbffcef5a 100644 --- a/types/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts +++ b/types/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts @@ -4,7 +4,21 @@ import nodemailer = require('nodemailer'); var opts: smtpTransport.SmtpOptions = { host: "localhost", - port: 25 + port: 25, + auth: { + type: 'OAuth2', + user: 'user@example.com', + // 3LO auth + clientId: '000000000000-xxx0.apps.googleusercontent.com', + clientSecret: 'XxxxxXXxX0xxxxxxxx0XXxX0', + refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx', + accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x', + expires: 1484314697598, + // 2LO auth (test only, dont mix with 3LO) + serviceClient: '113600000000000000000', + privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...', + }, + service: 'Gmail' }; var transport: nodemailer.Transport = smtpTransport(opts); diff --git a/types/number-to-words/index.d.ts b/types/number-to-words/index.d.ts new file mode 100644 index 0000000000..1d1caeb398 --- /dev/null +++ b/types/number-to-words/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for number-to-words 1.2 +// Project: https://github.com/marlun78/number-to-words +// Definitions by: Frederick Fogerty +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Converts an integer into a string with an ordinal postfix. If number is decimal, the decimals will be removed. + */ +export function toOrdinal(number: number): string; +/** + * Converts an integer into words. If number is decimal, the decimals will be removed. + */ +export function toWords(number: number): string; +/** + * Converts a number into ordinal words. If number is decimal, the decimals will be removed. + */ +export function toWordsOrdinal(number: number): string; diff --git a/types/number-to-words/number-to-words-tests.ts b/types/number-to-words/number-to-words-tests.ts new file mode 100644 index 0000000000..1c45936a78 --- /dev/null +++ b/types/number-to-words/number-to-words-tests.ts @@ -0,0 +1,7 @@ +import * as converter from 'number-to-words'; + +converter.toOrdinal(21); + +converter.toWords(13); + +converter.toWordsOrdinal(21); diff --git a/types/number-to-words/tsconfig.json b/types/number-to-words/tsconfig.json new file mode 100644 index 0000000000..c7d9661c4d --- /dev/null +++ b/types/number-to-words/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "number-to-words-tests.ts" + ] +} diff --git a/types/number-to-words/tslint.json b/types/number-to-words/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/number-to-words/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/nvd3/index.d.ts b/types/nvd3/index.d.ts index de2bbddefe..862aa38d99 100644 --- a/types/nvd3/index.d.ts +++ b/types/nvd3/index.d.ts @@ -67,7 +67,7 @@ declare namespace nv { } interface Nvd3TooltipStatic { - show([left, top]: [number, number], content: string, gravity?: string): void; //todo sort out use on nv.tooltip. + show(leftTop: [number, number], content: string, gravity?: string): void; //todo sort out use on nv.tooltip. cleanup(): void; //todo sort out use on nv.tooltip. } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 1b7f8424cb..520928823e 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -52,7 +52,7 @@ declare namespace Office { Excel, /** * Host is PowerPoint - */ + */ PowerPoint, /** * Host is Outlook @@ -64,12 +64,12 @@ declare namespace Office { OneNote, /** * Host is Project - */ + */ Project, /** * Host is Access */ - Access + Access } export enum PlatformType { /** @@ -2412,7 +2412,6 @@ declare module OfficeExtension { constructor(context: ClientRequestContext, parentObject: ClientObject, name: string, eventInfo: EventInfo); add(handler: (args: T) => IPromise): EventHandlerResult; remove(handler: (args: T) => IPromise): void; - removeAll(): void; } export class EventHandlerResult { @@ -2453,11 +2452,10 @@ declare module OfficeExtension { //////////////////////////////////////////////////////////////// -//////////////// Begin Excel APIs (latest = 1.3) /////////////// +/////////////////////// Begin Excel APIs /////////////////////// //////////////////////////////////////////////////////////////// - -declare module Excel { +declare namespace Excel { interface ThreeArrowsSet { [index: number]: Icon; redDownArrow: Icon; @@ -2616,6 +2614,65 @@ declare module Excel { fiveBoxes: FiveBoxesSet; } var icons: IconCollections; + /** + * Provides connection session for a remote workbook. + */ + class Session { + private static WorkbookSessionIdHeaderName; + private static WorkbookSessionIdHeaderNameLower; + constructor(workbookUrl?: string, requestHeaders?: { + [name: string]: string; + }, persisted?: boolean); + /** + * Close the session. + */ + close(): OfficeExtension.IPromise; + } + /** + * The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. + */ + class RequestContext extends OfficeExtension.ClientRequestContext { + constructor(url?: string | Session); + readonly workbook: Workbook; + readonly application: Application; + } + /** + * Executes a batch script that performs actions on the Excel object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using a new remote RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo | Session, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo | Session, object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the RequestContext of previously-created API objects. + * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of previously-created API objects. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo | Session, objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; /** * * Provides information about the binding that raised the SelectionChanged event. @@ -2689,6 +2746,21 @@ declare module Excel { */ workbook: Excel.Workbook; } + /** + * + * Provides information about the setting that raised the SettingsChanged event + * + * [Api set: ExcelApi 1.4] + */ + interface SettingsChangedEventArgs { + /** + * + * Gets the Setting object that represents the binding that raised the SettingsChanged event + * + * [Api set: ExcelApi 1.4] + */ + settings: Excel.SettingCollection; + } /** * * Represents the Excel application that manages the workbook. @@ -2702,16 +2774,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - calculationMode: string; + readonly calculationMode: string; /** * * Recalculate all currently opened workbooks in Excel. * - * @param calculationType Specifies the calculation type to use. See Excel.CalculationType for details. - * * [Api set: ExcelApi 1.1] + * + * @param calculationType Specifies the calculation type to use. See Excel.CalculationType for details. */ calculate(calculationType: string): void; + /** + * + * Suspends calculation until the next "context.sync()" is called. Once set, it is the developer's responsibility to re-calc the workbook, to ensure that any dependencies are propagated. + * + * [Api set: ExcelApi 1.7 (PREVIEW)] + */ + suspendApiCalculationUntilNextSync(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2733,49 +2812,63 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - application: Excel.Application; + readonly application: Excel.Application; /** * * Represents a collection of bindings that are part of the workbook. Read-only. * * [Api set: ExcelApi 1.1] */ - bindings: Excel.BindingCollection; + readonly bindings: Excel.BindingCollection; + /** + * + * Represents the collection of custom XML parts contained by this workbook. Read-only. + * + * [Api set: ExcelApi 1.5] + */ + readonly customXmlParts: Excel.CustomXmlPartCollection; /** * * Represents Excel application instance that contains this workbook. Read-only. * * [Api set: ExcelApi 1.2] */ - functions: Excel.Functions; + readonly functions: Excel.Functions; /** * * Represents a collection of workbook scoped named items (named ranges and constants). Read-only. * * [Api set: ExcelApi 1.1] */ - names: Excel.NamedItemCollection; + readonly names: Excel.NamedItemCollection; /** * * Represents a collection of PivotTables associated with the workbook. Read-only. * * [Api set: ExcelApi 1.3] */ - pivotTables: Excel.PivotTableCollection; + readonly pivotTables: Excel.PivotTableCollection; + /** + * + * Represents a collection of Settings associated with the workbook. Read-only. + * + * [Api set: ExcelApi 1.4] + */ + readonly settings: Excel.SettingCollection; /** * * Represents a collection of tables associated with the workbook. Read-only. * * [Api set: ExcelApi 1.1] */ - tables: Excel.TableCollection; + readonly tables: Excel.TableCollection; /** * * Represents a collection of worksheets associated with the workbook. Read-only. * * [Api set: ExcelApi 1.1] */ - worksheets: Excel.WorksheetCollection; + readonly worksheets: Excel.WorksheetCollection; /** * * Gets the currently selected range from the workbook. @@ -2793,7 +2886,7 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - onSelectionChanged: OfficeExtension.EventHandlers; + readonly onSelectionChanged: OfficeExtension.EventHandlers; toJSON(): {}; } /** @@ -2809,35 +2902,42 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - charts: Excel.ChartCollection; + readonly charts: Excel.ChartCollection; + /** + * + * Collection of names scoped to the current worksheet. Read-only. + * + * [Api set: ExcelApi 1.4] + */ + readonly names: Excel.NamedItemCollection; /** * * Collection of PivotTables that are part of the worksheet. Read-only. * * [Api set: ExcelApi 1.3] */ - pivotTables: Excel.PivotTableCollection; + readonly pivotTables: Excel.PivotTableCollection; /** * * Returns sheet protection object for a worksheet. * * [Api set: ExcelApi 1.2] */ - protection: Excel.WorksheetProtection; + readonly protection: Excel.WorksheetProtection; /** * * Collection of tables that are part of the worksheet. Read-only. * * [Api set: ExcelApi 1.1] */ - tables: Excel.TableCollection; + readonly tables: Excel.TableCollection; /** * * Returns a value that uniquely identifies the worksheet in a given workbook. The value of the identifier remains the same even when the worksheet is renamed or moved. Read-only. * * [Api set: ExcelApi 1.1] */ - id: string; + readonly id: string; /** * * The display name of the worksheet. @@ -2859,6 +2959,15 @@ declare module Excel { * [Api set: ExcelApi 1.1 for reading visibility; 1.2 for setting it.] */ visibility: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.WorksheetUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Worksheet): void; /** * * Activate the worksheet in the Excel UI. @@ -2866,6 +2975,13 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ activate(): void; + /** + * + * Calculates all cells on a worksheet. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + calculate(markAllDirty: boolean): void; /** * * Deletes the worksheet from the workbook. @@ -2877,30 +2993,75 @@ declare module Excel { * * Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it's stays within the worksheet grid. * + * [Api set: ExcelApi 1.1] + * * @param row The row number of the cell to be retrieved. Zero-indexed. * @param column the column number of the cell to be retrieved. Zero-indexed. - * - * [Api set: ExcelApi 1.1] */ getCell(row: number, column: number): Excel.Range; + /** + * + * Gets the worksheet that follows this one. If there are no worksheets following this one, this method will throw an error. + * + * [Api set: ExcelApi 1.5] + * + * @param visibleOnly If true, considers only visible worksheets, skipping over any hidden ones. + */ + getNext(visibleOnly?: boolean): Excel.Worksheet; + /** + * + * Gets the worksheet that follows this one. If there are no worksheets following this one, this method will return a null object. + * + * [Api set: ExcelApi 1.5] + * + * @param visibleOnly If true, considers only visible worksheets, skipping over any hidden ones. + */ + getNextOrNullObject(visibleOnly?: boolean): Excel.Worksheet; + /** + * + * Gets the worksheet that precedes this one. If there are no previous worksheets, this method will throw an error. + * + * [Api set: ExcelApi 1.5] + * + * @param visibleOnly If true, considers only visible worksheets, skipping over any hidden ones. + */ + getPrevious(visibleOnly?: boolean): Excel.Worksheet; + /** + * + * Gets the worksheet that precedes this one. If there are no previous worksheets, this method will return a null objet. + * + * [Api set: ExcelApi 1.5] + * + * @param visibleOnly If true, considers only visible worksheets, skipping over any hidden ones. + */ + getPreviousOrNullObject(visibleOnly?: boolean): Excel.Worksheet; /** * * Gets the range object specified by the address or name. * - * @param address The address or the name of the range. If not specified, the entire worksheet range is returned. - * * [Api set: ExcelApi 1.1] + * + * @param address The address or the name of the range. If not specified, the entire worksheet range is returned. */ getRange(address?: string): Excel.Range; /** * - * The used range is the smallest range that encompasses any cells that have a value or formatting assigned to them. If the worksheet is blank, this function will return the top left cell. - * - * @param valuesOnly Considers only cells with values as used cells (ignores formatting). [Api set: ExcelApi 1.2] + * The used range is the smallest range that encompasses any cells that have a value or formatting assigned to them. If the entire worksheet is blank, this function will return the top left cell (i.e.,: it will *not* throw an error). * * [Api set: ExcelApi 1.1] + * + * @param valuesOnly Considers only cells with values as used cells (ignoring formatting). [Api set: ExcelApi 1.2] */ getUsedRange(valuesOnly?: boolean): Excel.Range; + /** + * + * The used range is the smallest range that encompasses any cells that have a value or formatting assigned to them. If the entire worksheet is blank, this function will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param valuesOnly Considers only cells with values as used cells. + */ + getUsedRangeOrNullObject(valuesOnly?: boolean): Excel.Range; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2921,14 +3082,14 @@ declare module Excel { */ class WorksheetCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Adds a new worksheet to the workbook. The worksheet will be added at the end of existing worksheets. If you wish to activate the newly added worksheet, call ".activate() on it. * - * @param name The name of the worksheet to be added. If specified, name should be unqiue. If not specified, Excel determines the name of the new worksheet. - * * [Api set: ExcelApi 1.1] + * + * @param name The name of the worksheet to be added. If specified, name should be unqiue. If not specified, Excel determines the name of the new worksheet. */ add(name?: string): Excel.Worksheet; /** @@ -2938,15 +3099,47 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getActiveWorksheet(): Excel.Worksheet; + /** + * + * Gets the number of worksheets in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(visibleOnly?: boolean): OfficeExtension.ClientResult; + /** + * + * Gets the first worksheet in the collection. + If true, considers only visible worksheets, skipping over any hidden ones. + * + * [Api set: ExcelApi 1.5] + */ + getFirst(visibleOnly?: boolean): Excel.Worksheet; /** * * Gets a worksheet object using its Name or ID. * - * @param key The Name or ID of the worksheet. - * * [Api set: ExcelApi 1.1] + * + * @param key The Name or ID of the worksheet. */ getItem(key: string): Excel.Worksheet; + /** + * + * Gets a worksheet object using its Name or ID. If the worksheet does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param key The Name or ID of the worksheet. + */ + getItemOrNullObject(key: string): Excel.Worksheet; + /** + * + * Gets the last worksheet in the collection. + If true, considers only visible worksheets, skipping over any hidden ones. + * + * [Api set: ExcelApi 1.5] + */ + getLast(visibleOnly?: boolean): Excel.Worksheet; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2966,21 +3159,21 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - options: Excel.WorksheetProtectionOptions; + readonly options: Excel.WorksheetProtectionOptions; /** * * Indicates if the worksheet is protected. Read-Only. * * [Api set: ExcelApi 1.2] */ - protected: boolean; + readonly protected: boolean; /** * * Protects a worksheet. Fails if the worksheet has been protected. * - * @param options sheet protection options. - * * [Api set: ExcelApi 1.2] + * + * @param options sheet protection options. */ protect(options?: Excel.WorksheetProtectionOptions): void; /** @@ -3091,55 +3284,62 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Range extends OfficeExtension.ClientObject { + /** + * + * Collection of ConditionalFormats that intersect the range. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly conditionalFormats: Excel.ConditionalFormatCollection; /** * * Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only. * * [Api set: ExcelApi 1.1] */ - format: Excel.RangeFormat; + readonly format: Excel.RangeFormat; /** * * Represents the range sort of the current range. * * [Api set: ExcelApi 1.2] */ - sort: Excel.RangeSort; + readonly sort: Excel.RangeSort; /** * * The worksheet containing the current range. Read-only. * * [Api set: ExcelApi 1.1] */ - worksheet: Excel.Worksheet; + readonly worksheet: Excel.Worksheet; /** * * Represents the range reference in A1-style. Address value will contain the Sheet reference (e.g. Sheet1!A1:B4). Read-only. * * [Api set: ExcelApi 1.1] */ - address: string; + readonly address: string; /** * * Represents range reference for the specified range in the language of the user. Read-only. * * [Api set: ExcelApi 1.1] */ - addressLocal: string; + readonly addressLocal: string; /** * * Number of cells in the range. This API will return -1 if the cell count exceeds 2^31-1 (2,147,483,647). Read-only. * * [Api set: ExcelApi 1.1] */ - cellCount: number; + readonly cellCount: number; /** * * Represents the total number of columns in the range. Read-only. * * [Api set: ExcelApi 1.1] */ - columnCount: number; + readonly columnCount: number; /** * * Represents if all columns of the current range are hidden. @@ -3153,7 +3353,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - columnIndex: number; + readonly columnIndex: number; /** * * Represents the formula in A1-style notation. @@ -3181,7 +3381,7 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - hidden: boolean; + readonly hidden: boolean; /** * * Represents Excel's number format code for the given cell. @@ -3195,7 +3395,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - rowCount: number; + readonly rowCount: number; /** * * Represents if all rows of the current range are hidden. @@ -3209,21 +3409,21 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - rowIndex: number; + readonly rowIndex: number; /** * * Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only. * * [Api set: ExcelApi 1.1] */ - text: Array>; + readonly text: Array>; /** * * Represents the type of data of each cell. Read-only. * * [Api set: ExcelApi 1.1] */ - valueTypes: Array>; + readonly valueTypes: Array>; /** * * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. @@ -3231,80 +3431,96 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ values: Array>; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Range): void; + /** + * + * Calculates a range of cells on a worksheet. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + calculate(): void; /** * * Clear range values, format, fill, border, etc. * - * @param applyTo Determines the type of clear action. See Excel.ClearApplyTo for details. - * * [Api set: ExcelApi 1.1] + * + * @param applyTo Determines the type of clear action. See Excel.ClearApplyTo for details. */ clear(applyTo?: string): void; /** * * Deletes the cells associated with the range. * - * @param shift Specifies which way to shift the cells. See Excel.DeleteShiftDirection for details. - * * [Api set: ExcelApi 1.1] + * + * @param shift Specifies which way to shift the cells. See Excel.DeleteShiftDirection for details. */ delete(shift: string): void; /** * * Gets the smallest range object that encompasses the given ranges. For example, the GetBoundingRect of "B2:C5" and "D10:E15" is "B2:E16". * - * @param anotherRange The range object or address or range name. - * * [Api set: ExcelApi 1.1] + * + * @param anotherRange The range object or address or range name. */ getBoundingRect(anotherRange: Excel.Range | string): Excel.Range; /** * * Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it's stays within the worksheet grid. The returned cell is located relative to the top left cell of the range. * + * [Api set: ExcelApi 1.1] + * * @param row Row number of the cell to be retrieved. Zero-indexed. * @param column Column number of the cell to be retrieved. Zero-indexed. - * - * [Api set: ExcelApi 1.1] */ getCell(row: number, column: number): Excel.Range; /** * * Gets a column contained in the range. * - * @param column Column number of the range to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param column Column number of the range to be retrieved. Zero-indexed. */ getColumn(column: number): Excel.Range; /** * * Gets a certain number of columns to the right of the current Range object. * - * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. */ getColumnsAfter(count?: number): Excel.Range; /** * * Gets a certain number of columns to the left of the current Range object. * - * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. */ getColumnsBefore(count?: number): Excel.Range; /** * - * Gets an object that represents the entire column of the range. + * Gets an object that represents the entire column of the range (for example, if the current range represents cells "B4:E11", it's `getEntireColumn` is a range that represents columns "B:E"). * * [Api set: ExcelApi 1.1] */ getEntireColumn(): Excel.Range; /** * - * Gets an object that represents the entire row of the range. + * Gets an object that represents the entire row of the range (for example, if the current range represents cells "B4:E11", it's `GetEntireRow` is a range that represents rows "4:11"). * * [Api set: ExcelApi 1.1] */ @@ -3313,11 +3529,20 @@ declare module Excel { * * Gets the range object that represents the rectangular intersection of the given ranges. * - * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. - * * [Api set: ExcelApi 1.1] + * + * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. */ getIntersection(anotherRange: Excel.Range | string): Excel.Range; + /** + * + * Gets the range object that represents the rectangular intersection of the given ranges. If no intersection is found, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. + */ + getIntersectionOrNullObject(anotherRange: Excel.Range | string): Excel.Range; /** * * Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5". @@ -3341,60 +3566,69 @@ declare module Excel { getLastRow(): Excel.Range; /** * - * Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an exception will be thrown. + * Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an error will be thrown. + * + * [Api set: ExcelApi 1.1] * * @param rowOffset The number of rows (positive, negative, or 0) by which the range is to be offset. Positive values are offset downward, and negative values are offset upward. * @param columnOffset The number of columns (positive, negative, or 0) by which the range is to be offset. Positive values are offset to the right, and negative values are offset to the left. - * - * [Api set: ExcelApi 1.1] */ getOffsetRange(rowOffset: number, columnOffset: number): Excel.Range; /** * * Gets a Range object similar to the current Range object, but with its bottom-right corner expanded (or contracted) by some number of rows and columns. * + * [Api set: ExcelApi 1.2] + * * @param deltaRows The number of rows by which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. * @param deltaColumns The number of columnsby which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. - * - * [Api set: ExcelApi 1.2] */ getResizedRange(deltaRows: number, deltaColumns: number): Excel.Range; /** * * Gets a row contained in the range. * - * @param row Row number of the range to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param row Row number of the range to be retrieved. Zero-indexed. */ getRow(row: number): Excel.Range; /** * * Gets a certain number of rows above the current Range object. * - * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. */ getRowsAbove(count?: number): Excel.Range; /** * * Gets a certain number of rows below the current Range object. * - * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. */ getRowsBelow(count?: number): Excel.Range; /** * - * Returns the used range of the given range object. - * - * @param valuesOnly Considers only cells with values as used cells. [Api set: ExcelApi 1.2] + * Returns the used range of the given range object. If there are no used cells within the range, this function will throw an ItemNotFound error. * * [Api set: ExcelApi 1.1] + * + * @param valuesOnly Considers only cells with values as used cells. [Api set: ExcelApi 1.2] */ getUsedRange(valuesOnly?: boolean): Excel.Range; + /** + * + * Returns the used range of the given range object. If there are no used cells within the range, this function will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param valuesOnly Considers only cells with values as used cells. + */ + getUsedRangeOrNullObject(valuesOnly?: boolean): Excel.Range; /** * * Represents the visible rows of the current range. @@ -3406,18 +3640,18 @@ declare module Excel { * * Inserts a cell or a range of cells into the worksheet in place of this range, and shifts the other cells to make space. Returns a new Range object at the now blank space. * - * @param shift Specifies which way to shift the cells. See Excel.InsertShiftDirection for details. - * * [Api set: ExcelApi 1.1] + * + * @param shift Specifies which way to shift the cells. See Excel.InsertShiftDirection for details. */ insert(shift: string): Excel.Range; /** * * Merge the range cells into one region in the worksheet. * - * @param across Set true to merge cells in each row of the specified range as separate merged cells. The default value is false. - * * [Api set: ExcelApi 1.2] + * + * @param across Set true to merge cells in each row of the specified range as separate merged cells. The default value is false. */ merge(across?: boolean): void; /** @@ -3469,7 +3703,7 @@ declare module Excel { } /** * - * Represents a string reference of the form SheetName!A1:B5, or a global or local named range + * Represents a string reference of the form SheetName!A1:B5, or a global or local named range. * * [Api set: ExcelApi 1.2] */ @@ -3489,21 +3723,21 @@ declare module Excel { * * [Api set: ExcelApi 1.3] */ - rows: Excel.RangeViewCollection; + readonly rows: Excel.RangeViewCollection; /** * * Represents the cell addresses of the RangeView. * * [Api set: ExcelApi 1.3] */ - cellAddresses: Array>; + readonly cellAddresses: Array>; /** * * Returns the number of visible columns. Read-only. * * [Api set: ExcelApi 1.3] */ - columnCount: number; + readonly columnCount: number; /** * * Represents the formula in A1-style notation. @@ -3531,7 +3765,7 @@ declare module Excel { * * [Api set: ExcelApi 1.3] */ - index: number; + readonly index: number; /** * * Represents Excel's number format code for the given cell. @@ -3545,21 +3779,21 @@ declare module Excel { * * [Api set: ExcelApi 1.3] */ - rowCount: number; + readonly rowCount: number; /** * * Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only. * * [Api set: ExcelApi 1.3] */ - text: Array>; + readonly text: Array>; /** * * Represents the type of data of each cell. Read-only. * * [Api set: ExcelApi 1.3] */ - valueTypes: Array>; + readonly valueTypes: Array>; /** * * Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. @@ -3567,6 +3801,15 @@ declare module Excel { * [Api set: ExcelApi 1.3] */ values: Array>; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeViewUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: RangeView): void; /** * * Gets the parent range associated with the current RangeView. @@ -3594,20 +3837,27 @@ declare module Excel { } /** * - * Represents a collection of worksheet objects that are part of the workbook. + * Represents a collection of RangeView objects. * * [Api set: ExcelApi 1.3] */ class RangeViewCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; + /** + * + * Gets the number of RangeView objects in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a RangeView Row via it's index. Zero-Indexed. * - * @param index Index of the visible row. - * * [Api set: ExcelApi 1.3] + * + * @param index Index of the visible row. */ getItemAt(index: number): Excel.RangeView; /** @@ -3618,30 +3868,99 @@ declare module Excel { } /** * - * Setting represents a key-value pair of a setting persisted to the document. + * Represents a collection of worksheet objects that are part of the workbook. * - * [Api set: ExcelApi 1.3] + * [Api set: ExcelApi 1.4] */ - class Setting extends OfficeExtension.ClientObject { + class SettingCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; /** * - * Represents the value stored for this setting. + * Sets or adds the specified setting to the workbook. * - * [Api set: ExcelApi 1.3] + * [Api set: ExcelApi 1.4] + * + * @param key The Key of the new setting. + * @param value The Value for the new setting. */ - value: any; + add(key: string, value: string | number | boolean | Array | any): Excel.Setting; + /** + * + * Gets the number of Settings in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a Setting entry via the key. + * + * [Api set: ExcelApi 1.4] + * + * @param key Key of the setting. + */ + getItem(key: string): Excel.Setting; + /** + * + * Gets a Setting entry via the key. If the Setting does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param key The key of the setting. + */ + getItemOrNullObject(key: string): Excel.Setting; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.SettingCollection; + /** + * + * Occurs when the Settings in the document are changed. + * + * [Api set: ExcelApi 1.4] + */ + readonly onSettingsChanged: OfficeExtension.EventHandlers; + toJSON(): {}; + } + /** + * + * Setting represents a key-value pair of a setting persisted to the document. + * + * [Api set: ExcelApi 1.4] + */ + class Setting extends OfficeExtension.ClientObject { + private static DateJSONPrefix; + private static DateJSONSuffix; + private static replaceStringDateWithDate(value); /** * * Returns the key that represents the id of the Setting. Read-only. * - * [Api set: ExcelApi 1.3] + * [Api set: ExcelApi 1.4] */ - key: string; + readonly key: string; + /** + * + * Represents the value stored for this setting. + * + * [Api set: ExcelApi 1.4] + */ + value: any; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.SettingUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Setting): void; /** * * Deletes the setting. * - * [Api set: ExcelApi 1.3] + * [Api set: ExcelApi 1.4] */ delete(): void; /** @@ -3650,6 +3969,7 @@ declare module Excel { load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Setting; toJSON(): { "key": string; + "value": any; }; } /** @@ -3660,16 +3980,56 @@ declare module Excel { */ class NamedItemCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; + /** + * + * Adds a new name to the collection of the given scope. + * + * [Api set: ExcelApi 1.4] + * + * @param name The name of the named item. + * @param reference The formula or the range that the name will refer to. + * @param comment The comment associated with the named item + * @returns + */ + add(name: string, reference: Excel.Range | string, comment?: string): Excel.NamedItem; + /** + * + * Adds a new name to the collection of the given scope using the user's locale for the formula. + * + * [Api set: ExcelApi 1.4] + * + * @param name The "name" of the named item. + * @param formula The formula in the user's locale that the name will refer to. + * @param comment The comment associated with the named item + * @returns + */ + addFormulaLocal(name: string, formula: string, comment?: string): Excel.NamedItem; + /** + * + * Gets the number of named items in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a nameditem object using its name * - * @param name nameditem name. - * * [Api set: ExcelApi 1.1] + * + * @param name nameditem name. */ getItem(name: string): Excel.NamedItem; + /** + * + * Gets a nameditem object using its name. If the nameditem object does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param name nameditem name. + */ + getItemOrNullObject(name: string): Excel.NamedItem; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -3683,27 +4043,55 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class NamedItem extends OfficeExtension.ClientObject { + /** + * + * Returns the worksheet on which the named item is scoped to. Throws an error if the items is scoped to the workbook instead. + * + * [Api set: ExcelApi 1.4] + */ + readonly worksheet: Excel.Worksheet; + /** + * + * Returns the worksheet on which the named item is scoped to. Returns a null object if the item is scoped to the workbook instead. + * + * [Api set: ExcelApi 1.4] + */ + readonly worksheetOrNullObject: Excel.Worksheet; + /** + * + * Represents the comment associated with this name. + * + * [Api set: ExcelApi 1.4] + */ + comment: string; /** * * The name of the object. Read-only. * * [Api set: ExcelApi 1.1] */ - name: string; + readonly name: string; + /** + * + * Indicates whether the name is scoped to the workbook or to a specific worksheet. Read-only. + * + * [Api set: ExcelApi 1.4] + */ + readonly scope: string; /** * * Indicates the type of the value returned by the name's formula. See Excel.NamedItemType for details. Read-only. * * [Api set: ExcelApi 1.1] */ - type: string; + readonly type: string; /** * - * Represents the value computed by the name's formula. Read-only. + * Represents the value computed by the name's formula. For a named range, will return the range address. Read-only. * * [Api set: ExcelApi 1.1] */ - value: any; + readonly value: any; /** * * Specifies whether the object is visible or not. @@ -3711,18 +4099,34 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ visible: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.NamedItemUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: NamedItem): void; /** * - * Returns the range object that is associated with the name. Throws an exception if the named item's type is not a range. + * Deletes the given name. + * + * [Api set: ExcelApi 1.4] + */ + delete(): void; + /** + * + * Returns the range object that is associated with the name. Throws an error if the named item's type is not a range. * * [Api set: ExcelApi 1.1] */ getRange(): Excel.Range; /** * - * Returns the range object that is associated with the name. Returns a null object if the named item's type is not a range + * Returns the range object that is associated with the name. Returns a null object if the named item's type is not a range. * - * [Api set: ExcelApi 1.1] + * [Api set: ExcelApi 1.4] */ getRangeOrNullObject(): Excel.Range; /** @@ -3730,7 +4134,9 @@ declare module Excel { */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.NamedItem; toJSON(): { + "comment": string; "name": string; + "scope": string; "type": string; "value": any; "visible": boolean; @@ -3749,14 +4155,14 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - id: string; + readonly id: string; /** * * Returns the type of the binding. See Excel.BindingType for details. Read-only. * * [Api set: ExcelApi 1.1] */ - type: string; + readonly type: string; /** * * Deletes the binding. @@ -3795,14 +4201,14 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - onDataChanged: OfficeExtension.EventHandlers; + readonly onDataChanged: OfficeExtension.EventHandlers; /** * * Occurs when the selection is changed within the binding. * * [Api set: ExcelApi 1.2] */ - onSelectionChanged: OfficeExtension.EventHandlers; + readonly onSelectionChanged: OfficeExtension.EventHandlers; toJSON(): { "id": string; "type": string; @@ -3816,64 +4222,80 @@ declare module Excel { */ class BindingCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of bindings in the collection. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Add a new binding to a particular Range. * + * [Api set: ExcelApi 1.3] + * * @param range Range to bind the binding to. May be an Excel Range object, or a string. If string, must contain the full address, including the sheet name * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. - * - * [Api set: ExcelApi 1.3] */ add(range: Excel.Range | string, bindingType: string, id: string): Excel.Binding; /** * * Add a new binding based on a named item in the workbook. * + * [Api set: ExcelApi 1.3] + * * @param name Name from which to create binding. * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. - * - * [Api set: ExcelApi 1.3] */ addFromNamedItem(name: string, bindingType: string, id: string): Excel.Binding; /** * * Add a new binding based on the current selection. * + * [Api set: ExcelApi 1.3] + * * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. - * - * [Api set: ExcelApi 1.3] */ addFromSelection(bindingType: string, id: string): Excel.Binding; + /** + * + * Gets the number of bindings in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a binding object by ID. * - * @param id Id of the binding object to be retrieved. - * * [Api set: ExcelApi 1.1] + * + * @param id Id of the binding object to be retrieved. */ getItem(id: string): Excel.Binding; /** * * Gets a binding object based on its position in the items array. * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.Binding; + /** + * + * Gets a binding object by ID. If the binding object does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param id Id of the binding object to be retrieved. + */ + getItemOrNullObject(id: string): Excel.Binding; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -3890,42 +4312,58 @@ declare module Excel { */ class TableCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of tables in the workbook. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Create a new table. The range object or source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown. * + * [Api set: ExcelApi 1.1] + * * @param address A Range object, or a string address or name of the range representing the data source. If the address does not contain a sheet name, the currently-active sheet is used. [Api set: ExcelApi 1.1 for string parameter; 1.3 for accepting a Range object as well] * @param hasHeaders Boolean value that indicates whether the data being imported has column labels. If the source does not contain headers (i.e,. when this property set to false), Excel will automatically generate header shifting the data down by one row. - * - * [Api set: ExcelApi 1.1] */ add(address: Excel.Range | string, hasHeaders: boolean): Excel.Table; + /** + * + * Gets the number of tables in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a table by Name or ID. * - * @param key Name or ID of the table to be retrieved. - * * [Api set: ExcelApi 1.1] + * + * @param key Name or ID of the table to be retrieved. */ getItem(key: number | string): Excel.Table; /** * * Gets a table based on its position in the collection. * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.Table; + /** + * + * Gets a table by Name or ID. If the table does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param key Name or ID of the table to be retrieved. + */ + getItemOrNullObject(key: number | string): Excel.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -3947,28 +4385,28 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - columns: Excel.TableColumnCollection; + readonly columns: Excel.TableColumnCollection; /** * * Represents a collection of all the rows in the table. Read-only. * * [Api set: ExcelApi 1.1] */ - rows: Excel.TableRowCollection; + readonly rows: Excel.TableRowCollection; /** * * Represents the sorting for the table. * * [Api set: ExcelApi 1.2] */ - sort: Excel.TableSort; + readonly sort: Excel.TableSort; /** * * The worksheet containing the current table. Read-only. * * [Api set: ExcelApi 1.2] */ - worksheet: Excel.Worksheet; + readonly worksheet: Excel.Worksheet; /** * * Indicates whether the first column contains special formatting. @@ -3989,7 +4427,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - id: number; + readonly id: number; /** * * Name of the table. @@ -4039,6 +4477,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ style: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Table): void; /** * * Clears all the filters currently applied on the table. @@ -4120,43 +4567,59 @@ declare module Excel { */ class TableColumnCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of columns in the table. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Adds a new column to the table. * + * [Api set: ExcelApi 1.1 requires an index smaller than the total column count; 1.4 allows index to be optional (null or -1) and will append a column at the end; 1.4 allows name parameter at creation time.] + * * @param index Specifies the relative position of the new column. If null or -1, the addition happens at the end. Columns with a higher index will be shifted to the side. Zero-indexed. * @param values A 2-dimensional array of unformatted values of the table column. * @param name Specifies the name of the new column. If null, the default name will be used. - * - * [Api set: ExcelApi 1.1 requires an index smaller than the total column count; 1.4 allows index to be optional (null or -1) and will append a column at the end; 1.4 allows name parameter at creation time.] */ add(index?: number, values?: Array> | boolean | string | number, name?: string): Excel.TableColumn; + /** + * + * Gets the number of columns in the table. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a column object by Name or ID. * - * @param key Column Name or ID. - * * [Api set: ExcelApi 1.1] + * + * @param key Column Name or ID. */ getItem(key: number | string): Excel.TableColumn; /** * * Gets a column based on its position in the collection. * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.TableColumn; + /** + * + * Gets a column object by Name or ID. If the column does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param key Column Name or ID. + */ + getItemOrNullObject(key: number | string): Excel.TableColumn; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4178,21 +4641,21 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - filter: Excel.Filter; + readonly filter: Excel.Filter; /** * * Returns a unique key that identifies the column within the table. Read-only. * * [Api set: ExcelApi 1.1] */ - id: number; + readonly id: number; /** * * Returns the index number of the column within the columns collection of the table. Zero-indexed. Read-only. * * [Api set: ExcelApi 1.1] */ - index: number; + readonly index: number; /** * * Represents the name of the table column. @@ -4207,6 +4670,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ values: Array>; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableColumnUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableColumn): void; /** * * Deletes the column from the table. @@ -4256,36 +4728,58 @@ declare module Excel { /** * * Represents a collection of all the rows that are part of the table. + + Note that unlike Ranges or Columns, which will adjust if new rows/columns are added before them, + a TableRow object represent the physical location of the table row, but not the data. + That is, if the data is sorted or if new rows are added, a table row will continue + to point at the index for which it was created. * * [Api set: ExcelApi 1.1] */ class TableRowCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of rows in the table. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Adds one or more rows to the table. The return object will be the top of the newly added row(s). + + Note that unlike Ranges or Columns, which will adjust if new rows/columns are added before them, + a TableRow object represent the physical location of the table row, but not the data. + That is, if the data is sorted or if new rows are added, a table row will continue + to point at the index for which it was created. + * + * [Api set: ExcelApi 1.1 for adding a single row; 1.4 allows adding of multiple rows.] * * @param index Specifies the relative position of the new row. If null or -1, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed. * @param values A 2-dimensional array of unformatted values of the table row. - * - * [Api set: ExcelApi 1.1 for adding a single row; 1.4 allows adding of multiple rows.] */ add(index?: number, values?: Array> | boolean | string | number): Excel.TableRow; /** * - * Gets a row based on its position in the collection. + * Gets the number of rows in the table. * - * @param index Index value of the object to be retrieved. Zero-indexed. + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a row based on its position in the collection. + + Note that unlike Ranges or Columns, which will adjust if new rows/columns are added before them, + a TableRow object represent the physical location of the table row, but not the data. + That is, if the data is sorted or if new rows are added, a table row will continue + to point at the index for which it was created. * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.TableRow; /** @@ -4299,6 +4793,11 @@ declare module Excel { /** * * Represents a row in a table. + + Note that unlike Ranges or Columns, which will adjust if new rows/columns are added before them, + a TableRow object represent the physical location of the table row, but not the data. + That is, if the data is sorted or if new rows are added, a table row will continue + to point at the index for which it was created. * * [Api set: ExcelApi 1.1] */ @@ -4309,7 +4808,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - index: number; + readonly index: number; /** * * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. @@ -4317,6 +4816,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ values: Array>; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableRowUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableRow): void; /** * * Deletes the row from the table. @@ -4353,28 +4861,28 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - borders: Excel.RangeBorderCollection; + readonly borders: Excel.RangeBorderCollection; /** * * Returns the fill object defined on the overall range. Read-only. * * [Api set: ExcelApi 1.1] */ - fill: Excel.RangeFill; + readonly fill: Excel.RangeFill; /** * * Returns the font object defined on the overall range. Read-only. * * [Api set: ExcelApi 1.1] */ - font: Excel.RangeFont; + readonly font: Excel.RangeFont; /** * * Returns the format protection object for a range. * * [Api set: ExcelApi 1.2] */ - protection: Excel.FormatProtection; + readonly protection: Excel.FormatProtection; /** * * Gets or sets the width of all colums within the range. If the column widths are not uniform, null will be returned. @@ -4410,6 +4918,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ wrapText: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: RangeFormat): void; /** * * Changes the width of the columns of the current range to achieve the best fit, based on the current data in the columns. @@ -4460,6 +4977,15 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ locked: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.FormatProtectionUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: FormatProtection): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4483,6 +5009,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ color: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeFillUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: RangeFill): void; /** * * Resets the range background. @@ -4518,7 +5053,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - sideIndex: string; + readonly sideIndex: string; /** * * One of the constants of line style specifying the line style for the border. See Excel.BorderLineStyle for details. @@ -4533,6 +5068,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ weight: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeBorderUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: RangeBorder): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4546,36 +5090,36 @@ declare module Excel { } /** * - * Represents the border objects that make up range border. + * Represents the border objects that make up the range border. * * [Api set: ExcelApi 1.1] */ class RangeBorderCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Number of border objects in the collection. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Gets a border object using its name * - * @param index Index value of the border object to be retrieved. See Excel.BorderIndex for details. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the border object to be retrieved. See Excel.BorderIndex for details. */ getItem(index: string): Excel.RangeBorder; /** * * Gets a border object using its index * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.RangeBorder; /** @@ -4635,6 +5179,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ underline: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeFontUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: RangeFont): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4656,43 +5209,60 @@ declare module Excel { */ class ChartCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of charts in the worksheet. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; /** * * Creates a new chart. * + * [Api set: ExcelApi 1.1] + * * @param type Represents the type of a chart. See Excel.ChartType for details. * @param sourceData The Range object corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. - * - * [Api set: ExcelApi 1.1] */ add(type: string, sourceData: Excel.Range, seriesBy?: string): Excel.Chart; + /** + * + * Returns the number of charts in the worksheet. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. * - * @param name Name of the chart to be retrieved. - * * [Api set: ExcelApi 1.1] + * + * @param name Name of the chart to be retrieved. */ getItem(name: string): Excel.Chart; /** * * Gets a chart based on its position in the collection. * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.Chart; + /** + * + * Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. + If the chart does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param name Name of the chart to be retrieved. + */ + getItemOrNullObject(name: string): Excel.Chart; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4714,49 +5284,49 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - axes: Excel.ChartAxes; + readonly axes: Excel.ChartAxes; /** * * Represents the datalabels on the chart. Read-only. * * [Api set: ExcelApi 1.1] */ - dataLabels: Excel.ChartDataLabels; + readonly dataLabels: Excel.ChartDataLabels; /** * * Encapsulates the format properties for the chart area. Read-only. * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartAreaFormat; + readonly format: Excel.ChartAreaFormat; /** * * Represents the legend for the chart. Read-only. * * [Api set: ExcelApi 1.1] */ - legend: Excel.ChartLegend; + readonly legend: Excel.ChartLegend; /** * * Represents either a single series or collection of series in the chart. Read-only. * * [Api set: ExcelApi 1.1] */ - series: Excel.ChartSeriesCollection; + readonly series: Excel.ChartSeriesCollection; /** * * Represents the title of the specified chart, including the text, visibility, position and formating of the title. Read-only. * * [Api set: ExcelApi 1.1] */ - title: Excel.ChartTitle; + readonly title: Excel.ChartTitle; /** * * The worksheet containing the current chart. Read-only. * * [Api set: ExcelApi 1.2] */ - worksheet: Excel.Worksheet; + readonly worksheet: Excel.Worksheet; /** * * Represents the height, in points, of the chart object. @@ -4792,6 +5362,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Chart): void; /** * * Deletes the chart object. @@ -4804,31 +5383,31 @@ declare module Excel { * Renders the chart as a base64-encoded image by scaling the chart to fit the specified dimensions. The aspect ratio is preserved as part of the resizing. * + * [Api set: ExcelApi 1.2] + * * @param height (Optional) The desired height of the resulting image. * @param width (Optional) The desired width of the resulting image. * @param fittingMode (Optional) The method used to scale the chart to the specified to the specified dimensions (if both height and width are set)." - * - * [Api set: ExcelApi 1.2] */ getImage(width?: number, height?: number, fittingMode?: string): OfficeExtension.ClientResult; /** * * Resets the source data for the chart. * + * [Api set: ExcelApi 1.1] + * * @param sourceData The Range object corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, Columns. See Excel.ChartSeriesBy for details. - * - * [Api set: ExcelApi 1.1] */ setData(sourceData: Excel.Range, seriesBy?: string): void; /** * * Positions the chart relative to cells on the worksheet. * + * [Api set: ExcelApi 1.1] + * * @param startCell The start cell. This is where the chart will be moved to. The start cell is the top-left or top-right cell, depending on the user's right-to-left display settings. * @param endCell (Optional) The end cell. If specified, the chart's width and height will be set to fully cover up this cell/range. - * - * [Api set: ExcelApi 1.1] */ setPosition(startCell: Excel.Range | string, endCell?: Excel.Range | string): void; /** @@ -4861,14 +5440,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * * Represents the font attributes (font name, font size, color, etc.) for the current object. Read-only. * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAreaFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAreaFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4886,21 +5474,28 @@ declare module Excel { */ class ChartSeriesCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * * Returns the number of series in the collection. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; + /** + * + * Returns the number of series in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Retrieves a series based on its position in the collection * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.ChartSeries; /** @@ -4924,14 +5519,14 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartSeriesFormat; + readonly format: Excel.ChartSeriesFormat; /** * * Represents a collection of all points in the series. Read-only. * * [Api set: ExcelApi 1.1] */ - points: Excel.ChartPointsCollection; + readonly points: Excel.ChartPointsCollection; /** * * Represents the name of a series in a chart. @@ -4939,6 +5534,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ name: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartSeriesUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartSeries): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4961,14 +5565,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * * Represents line formatting. Read-only. * * [Api set: ExcelApi 1.1] */ - line: Excel.ChartLineFormat; + readonly line: Excel.ChartLineFormat; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartSeriesFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartSeriesFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4986,21 +5599,28 @@ declare module Excel { */ class ChartPointsCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; /** * - * Returns the number of chart points in the collection. Read-only. + * Returns the number of chart points in the series. Read-only. * * [Api set: ExcelApi 1.1] */ - count: number; + readonly count: number; + /** + * + * Returns the number of chart points in the series. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Retrieve a point based on its position within the series. * - * @param index Index value of the object to be retrieved. Zero-indexed. - * * [Api set: ExcelApi 1.1] + * + * @param index Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.ChartPoint; /** @@ -5024,14 +5644,14 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartPointFormat; + readonly format: Excel.ChartPointFormat; /** * * Returns the value of a chart point. Read-only. * * [Api set: ExcelApi 1.1] */ - value: any; + readonly value: any; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5054,7 +5674,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5076,21 +5696,30 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - categoryAxis: Excel.ChartAxis; + readonly categoryAxis: Excel.ChartAxis; /** * * Represents the series axis of a 3-dimensional chart. Read-only. * * [Api set: ExcelApi 1.1] */ - seriesAxis: Excel.ChartAxis; + readonly seriesAxis: Excel.ChartAxis; /** * * Represents the value axis in an axis. Read-only. * * [Api set: ExcelApi 1.1] */ - valueAxis: Excel.ChartAxis; + readonly valueAxis: Excel.ChartAxis; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAxesUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAxes): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5114,28 +5743,28 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartAxisFormat; + readonly format: Excel.ChartAxisFormat; /** * * Returns a gridlines object that represents the major gridlines for the specified axis. Read-only. * * [Api set: ExcelApi 1.1] */ - majorGridlines: Excel.ChartGridlines; + readonly majorGridlines: Excel.ChartGridlines; /** * * Returns a Gridlines object that represents the minor gridlines for the specified axis. Read-only. * * [Api set: ExcelApi 1.1] */ - minorGridlines: Excel.ChartGridlines; + readonly minorGridlines: Excel.ChartGridlines; /** * * Represents the axis title. Read-only. * * [Api set: ExcelApi 1.1] */ - title: Excel.ChartAxisTitle; + readonly title: Excel.ChartAxisTitle; /** * * Represents the interval between two major tick marks. Can be set to a numeric value or an empty string. The returned value is always a number. @@ -5164,6 +5793,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ minorUnit: any; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAxisUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAxis): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5192,14 +5830,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; /** * * Represents chart line formatting. Read-only. * * [Api set: ExcelApi 1.1] */ - line: Excel.ChartLineFormat; + readonly line: Excel.ChartLineFormat; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAxisFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAxisFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5222,7 +5869,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartAxisTitleFormat; + readonly format: Excel.ChartAxisTitleFormat; /** * * Represents the axis title. @@ -5237,6 +5884,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ visible: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAxisTitleUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAxisTitle): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5260,7 +5916,16 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartAxisTitleFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartAxisTitleFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5282,7 +5947,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartDataLabelFormat; + readonly format: Excel.ChartDataLabelFormat; /** * * DataLabelPosition value that represents the position of the data label. See Excel.ChartDataLabelPosition for details. @@ -5339,6 +6004,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ showValue: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartDataLabelsUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartDataLabels): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5368,14 +6042,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * * Represents the font attributes (font name, font size, color, etc.) for a chart data label. Read-only. * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartDataLabelFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartDataLabelFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5398,7 +6081,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartGridlinesFormat; + readonly format: Excel.ChartGridlinesFormat; /** * * Boolean value representing if the axis gridlines are visible or not. @@ -5406,6 +6089,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ visible: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartGridlinesUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartGridlines): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5428,7 +6120,16 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - line: Excel.ChartLineFormat; + readonly line: Excel.ChartLineFormat; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartGridlinesFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartGridlinesFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5450,7 +6151,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartLegendFormat; + readonly format: Excel.ChartLegendFormat; /** * * Boolean value for whether the chart legend should overlap with the main body of the chart. @@ -5472,6 +6173,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ visible: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartLegendUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartLegend): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5496,14 +6206,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * * Represents the font attributes such as font name, font size, color, etc. of a chart legend. Read-only. * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartLegendFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartLegendFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5526,7 +6245,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - format: Excel.ChartTitleFormat; + readonly format: Excel.ChartTitleFormat; /** * * Boolean value representing if the chart title will overlay the chart or not. @@ -5548,6 +6267,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ visible: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartTitleUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartTitle): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5572,14 +6300,23 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - fill: Excel.ChartFill; + readonly fill: Excel.ChartFill; /** * * Represents the font attributes (font name, font size, color, etc.) for an object. Read-only. * * [Api set: ExcelApi 1.1] */ - font: Excel.ChartFont; + readonly font: Excel.ChartFont; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartTitleFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartTitleFormat): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5611,9 +6348,9 @@ declare module Excel { * * Sets the fill formatting of a chart element to a uniform color. * - * @param color HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). - * * [Api set: ExcelApi 1.1] + * + * @param color HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). */ setSolidColor(color: string): void; toJSON(): {}; @@ -5632,6 +6369,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ color: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartLineFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartLineFormat): void; /** * * Clear the line format of a chart element. @@ -5696,6 +6442,15 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ underline: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ChartFontUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ChartFont): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -5720,13 +6475,13 @@ declare module Excel { * * Perform a sort operation. * + * [Api set: ExcelApi 1.2] + * * @param fields The list of conditions to sort on. * @param matchCase Whether to have the casing impact string ordering. * @param hasHeaders Whether the range has a header. * @param orientation Whether the operation is sorting rows or columns. * @param method The ordering method used for Chinese characters. - * - * [Api set: ExcelApi 1.2] */ apply(fields: Array, matchCase?: boolean, hasHeaders?: boolean, orientation?: string, method?: string): void; toJSON(): {}; @@ -5744,30 +6499,30 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - fields: Array; + readonly fields: Array; /** * * Represents whether the casing impacted the last sort of the table. * * [Api set: ExcelApi 1.2] */ - matchCase: boolean; + readonly matchCase: boolean; /** * * Represents Chinese character ordering method last used to sort the table. * * [Api set: ExcelApi 1.2] */ - method: string; + readonly method: string; /** * * Perform a sort operation. * + * [Api set: ExcelApi 1.2] + * * @param fields The list of conditions to sort on. * @param matchCase Whether to have the casing impact string ordering. * @param method The ordering method used for Chinese characters. - * - * [Api set: ExcelApi 1.2] */ apply(fields: Array, matchCase?: boolean, method?: string): void; /** @@ -5857,106 +6612,106 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - criteria: Excel.FilterCriteria; + readonly criteria: Excel.FilterCriteria; /** * * Apply the given filter criteria on the given column. * - * @param criteria The criteria to apply. - * * [Api set: ExcelApi 1.2] + * + * @param criteria The criteria to apply. */ apply(criteria: Excel.FilterCriteria): void; /** * * Apply a "Bottom Item" filter to the column for the given number of elements. * - * @param count The number of elements from the bottom to show. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of elements from the bottom to show. */ applyBottomItemsFilter(count: number): void; /** * * Apply a "Bottom Percent" filter to the column for the given percentage of elements. * - * @param percent The percentage of elements from the bottom to show. - * * [Api set: ExcelApi 1.2] + * + * @param percent The percentage of elements from the bottom to show. */ applyBottomPercentFilter(percent: number): void; /** * * Apply a "Cell Color" filter to the column for the given color. * - * @param color The background color of the cells to show. - * * [Api set: ExcelApi 1.2] + * + * @param color The background color of the cells to show. */ applyCellColorFilter(color: string): void; /** * * Apply a "Icon" filter to the column for the given criteria strings. * + * [Api set: ExcelApi 1.2] + * * @param criteria1 The first criteria string. * @param criteria2 The second criteria string. * @param oper The operator that describes how the two criteria are joined. - * - * [Api set: ExcelApi 1.2] */ applyCustomFilter(criteria1: string, criteria2?: string, oper?: string): void; /** * * Apply a "Dynamic" filter to the column. * - * @param criteria The dynamic criteria to apply. - * * [Api set: ExcelApi 1.2] + * + * @param criteria The dynamic criteria to apply. */ applyDynamicFilter(criteria: string): void; /** * * Apply a "Font Color" filter to the column for the given color. * - * @param color The font color of the cells to show. - * * [Api set: ExcelApi 1.2] + * + * @param color The font color of the cells to show. */ applyFontColorFilter(color: string): void; /** * * Apply a "Icon" filter to the column for the given icon. * - * @param icon The icons of the cells to show. - * * [Api set: ExcelApi 1.2] + * + * @param icon The icons of the cells to show. */ applyIconFilter(icon: Excel.Icon): void; /** * * Apply a "Top Item" filter to the column for the given number of elements. * - * @param count The number of elements from the top to show. - * * [Api set: ExcelApi 1.2] + * + * @param count The number of elements from the top to show. */ applyTopItemsFilter(count: number): void; /** * * Apply a "Top Percent" filter to the column for the given percentage of elements. * - * @param percent The percentage of elements from the top to show. - * * [Api set: ExcelApi 1.2] + * + * @param percent The percentage of elements from the top to show. */ applyTopPercentFilter(percent: number): void; /** * * Apply a "Values" filter to the column for the given values. * - * @param values The list of values to show. - * * [Api set: ExcelApi 1.2] + * + * @param values The list of values to show. */ applyValuesFilter(values: Array): void; /** @@ -5992,7 +6747,7 @@ declare module Excel { * * The first criterion used to filter data. Used as an operator in the case of "custom" filtering. For example ">50" for number greater than 50 or "=*s" for values ending in "s". - + Used as a number in the case of top/bottom items/percents. E.g. "5" for the top 5 items if filterOn is set to "topItems" * * [Api set: ExcelApi 1.2] @@ -6085,6 +6840,177 @@ declare module Excel { */ set: string; } + /** + * + * A scoped collection of custom XML parts. + A scoped collection is the result of some operation, e.g. filtering by namespace. + A scoped collection cannot be scoped any further. + * + * [Api set: ExcelApi 1.5] + */ + class CustomXmlPartScopedCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of CustomXML parts in this collection. + * + * [Api set: ExcelApi 1.5] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a custom XML part based on its ID. + * + * [Api set: ExcelApi 1.5] + * + * @param id ID of the object to be retrieved. + */ + getItem(id: string): Excel.CustomXmlPart; + /** + * + * Gets a custom XML part based on its ID. + If the CustomXmlPart does not exist, the return object's isNull property will be true. + * + * [Api set: ExcelApi 1.5] + * + * @param id ID of the object to be retrieved. + */ + getItemOrNullObject(id: string): Excel.CustomXmlPart; + /** + * + * If the collection contains exactly one item, this method returns it. + Otherwise, this method produces an error. + * + * [Api set: ExcelApi 1.5] + */ + getOnlyItem(): Excel.CustomXmlPart; + /** + * + * If the collection contains exactly one item, this method returns it. + Otherwise, this method returns Null. + * + * [Api set: ExcelApi 1.5] + */ + getOnlyItemOrNullObject(): Excel.CustomXmlPart; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.CustomXmlPartScopedCollection; + toJSON(): {}; + } + /** + * + * A collection of custom XML parts. + * + * [Api set: ExcelApi 1.5] + */ + class CustomXmlPartCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Adds a new custom XML part to the workbook. + * + * [Api set: ExcelApi 1.5] + * + * @param xml XML content. Must be a valid XML fragment. + */ + add(xml: string): Excel.CustomXmlPart; + /** + * + * Gets a new scoped collection of custom XML parts whose namespaces match the given namespace. + * + * [Api set: ExcelApi 1.5] + * + * @param namespaceUri + */ + getByNamespace(namespaceUri: string): Excel.CustomXmlPartScopedCollection; + /** + * + * Gets the number of CustomXml parts in the collection. + * + * [Api set: ExcelApi 1.5] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a custom XML part based on its ID. + * + * [Api set: ExcelApi 1.5] + * + * @param id ID of the object to be retrieved. + */ + getItem(id: string): Excel.CustomXmlPart; + /** + * + * Gets a custom XML part based on its ID. + If the CustomXmlPart does not exist, the return object's isNull property will be true. + * + * [Api set: ExcelApi 1.5] + * + * @param id ID of the object to be retrieved. + */ + getItemOrNullObject(id: string): Excel.CustomXmlPart; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.CustomXmlPartCollection; + toJSON(): {}; + } + /** + * + * Represents a custom XML part object in a workbook. + * + * [Api set: ExcelApi 1.5] + */ + class CustomXmlPart extends OfficeExtension.ClientObject { + /** + * + * The custom XML part's ID. Read-only. + * + * [Api set: ExcelApi 1.5] + */ + readonly id: string; + /** + * + * The custom XML part's namespace URI. Read-only. + * + * [Api set: ExcelApi 1.5] + */ + readonly namespaceUri: string; + /** + * + * Deletes the custom XML part. + * + * [Api set: ExcelApi 1.5] + */ + delete(): void; + /** + * + * Gets the custom XML part's full XML content. + * + * [Api set: ExcelApi 1.5] + */ + getXml(): OfficeExtension.ClientResult; + /** + * + * Sets the custom XML part's full XML content. + * + * [Api set: ExcelApi 1.5] + * + * @param xml XML content for the part. + */ + setXml(xml: string): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.CustomXmlPart; + toJSON(): { + "id": string; + "namespaceUri": string; + }; + } /** * * Represents a collection of all the PivotTables that are part of the workbook or worksheet. @@ -6093,19 +7019,35 @@ declare module Excel { */ class PivotTableCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ - items: Array; + readonly items: Array; + /** + * + * Gets the number of pivot tables in the collection. + * + * [Api set: ExcelApi 1.4] + */ + getCount(): OfficeExtension.ClientResult; /** * * Gets a PivotTable by name. * - * @param name Name of the PivotTable to be retrieved. - * * [Api set: ExcelApi 1.3] + * + * @param name Name of the PivotTable to be retrieved. */ getItem(name: string): Excel.PivotTable; /** * - * Refreshes all the PivotTables in the collection. + * Gets a PivotTable by name. If the PivotTable does not exist, will return a null object. + * + * [Api set: ExcelApi 1.4] + * + * @param name Name of the PivotTable to be retrieved. + */ + getItemOrNullObject(name: string): Excel.PivotTable; + /** + * + * Refreshes all the pivot tables in the collection. * * [Api set: ExcelApi 1.3] */ @@ -6129,7 +7071,14 @@ declare module Excel { * * [Api set: ExcelApi 1.3] */ - worksheet: Excel.Worksheet; + readonly worksheet: Excel.Worksheet; + /** + * + * Id of the PivotTable. + * + * [Api set: ExcelApi 1.5] + */ + readonly id: string; /** * * Name of the PivotTable. @@ -6137,6 +7086,15 @@ declare module Excel { * [Api set: ExcelApi 1.3] */ name: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.PivotTableUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: PivotTable): void; /** * * Refreshes the PivotTable. @@ -6149,13 +7107,1276 @@ declare module Excel { */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTable; toJSON(): { + "id": string; "name": string; }; } + /** + * + * Represents a collection of all the conditional formats that are overlap the range. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalFormatCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Adds a new conditional format to the collection at the first/top priority. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + * + * @param type The type of conditional format being added. See Excel.ConditionalFormatType for details. + */ + add(type: string): Excel.ConditionalFormat; + /** + * + * Clears all conditional formats active on the current specified range. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + clearAll(): void; + /** + * + * Returns the number of conditional formats in the workbook. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Returns a conditional format at the given index. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + * + * @param index Index of the conditional formats to be retrieved. + */ + getItemAt(index: number): Excel.ConditionalFormat; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalFormatCollection; + toJSON(): {}; + } + /** + * + * An object encapsulating a conditional format's range, format, rule, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns the cell value conditional format properties if the current conditional format is a CellValue type. + For example to format all cells between 5 and 10. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly cellValue: Excel.CellValueConditionalFormat; + /** + * + * Returns the cell value conditional format properties if the current conditional format is a CellValue type. + For example to format all cells between 5 and 10. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly cellValueOrNullObject: Excel.CellValueConditionalFormat; + /** + * + * Returns the ColorScale conditional format properties if the current conditional format is an ColorScale type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly colorScale: Excel.ColorScaleConditionalFormat; + /** + * + * Returns the ColorScale conditional format properties if the current conditional format is an ColorScale type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly colorScaleOrNullObject: Excel.ColorScaleConditionalFormat; + /** + * + * Returns the custom conditional format properties if the current conditional format is a custom type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly custom: Excel.CustomConditionalFormat; + /** + * + * Returns the custom conditional format properties if the current conditional format is a custom type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly customOrNullObject: Excel.CustomConditionalFormat; + /** + * + * Returns the data bar properties if the current conditional format is a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly dataBar: Excel.DataBarConditionalFormat; + /** + * + * Returns the data bar properties if the current conditional format is a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly dataBarOrNullObject: Excel.DataBarConditionalFormat; + /** + * + * Returns the IconSet conditional format properties if the current conditional format is an IconSet type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly iconSet: Excel.IconSetConditionalFormat; + /** + * + * Returns the IconSet conditional format properties if the current conditional format is an IconSet type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly iconSetOrNullObject: Excel.IconSetConditionalFormat; + /** + * + * Returns the preset criteria conditional format such as above average/below average/unique values/contains blank/nonblank/error/noerror properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly preset: Excel.PresetCriteriaConditionalFormat; + /** + * + * Returns the preset criteria conditional format such as above average/below average/unique values/contains blank/nonblank/error/noerror properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly presetOrNullObject: Excel.PresetCriteriaConditionalFormat; + /** + * + * Returns the specific text conditional format properties if the current conditional format is a text type. + For example to format cells matching the word "Text". + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly textComparison: Excel.TextConditionalFormat; + /** + * + * Returns the specific text conditional format properties if the current conditional format is a text type. + For example to format cells matching the word "Text". + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly textComparisonOrNullObject: Excel.TextConditionalFormat; + /** + * + * Returns the Top/Bottom conditional format properties if the current conditional format is an TopBottom type. + For example to format the top 10% or bottom 10 items. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly topBottom: Excel.TopBottomConditionalFormat; + /** + * + * Returns the Top/Bottom conditional format properties if the current conditional format is an TopBottom type. + For example to format the top 10% or bottom 10 items. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly topBottomOrNullObject: Excel.TopBottomConditionalFormat; + /** + * + * The priority (or index) within the conditional format collection that this conditional format currently exists in. Changing this also + changes other conditional formats' priorities, to allow for a contiguous priority order. + Use a negative priority to begin from the back. + Priorities greater than than bounds will get and set to the maximum (or minimum if negative) priority. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + priority: number; + /** + * + * If the conditions of this conditional format are met, no lower-priority formats shall take effect on that cell. + Null on databars, icon sets, and colorscales as there's no concept of StopIfTrue for these + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + stopIfTrue: boolean; + /** + * + * A type of conditional format. Only one can be set at a time. Read-Only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly type: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalFormat): void; + /** + * + * Deletes this conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + delete(): void; + /** + * + * Returns the range the conditonal format is applied to or a null object if the range is discontiguous. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + getRange(): Excel.Range; + /** + * + * Returns the range the conditonal format is applied to or a null object if the range is discontiguous. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + getRangeOrNullObject(): Excel.Range; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalFormat; + toJSON(): { + "cellValue": CellValueConditionalFormat; + "cellValueOrNullObject": CellValueConditionalFormat; + "colorScale": ColorScaleConditionalFormat; + "colorScaleOrNullObject": ColorScaleConditionalFormat; + "custom": CustomConditionalFormat; + "customOrNullObject": CustomConditionalFormat; + "dataBar": DataBarConditionalFormat; + "dataBarOrNullObject": DataBarConditionalFormat; + "iconSet": IconSetConditionalFormat; + "iconSetOrNullObject": IconSetConditionalFormat; + "preset": PresetCriteriaConditionalFormat; + "presetOrNullObject": PresetCriteriaConditionalFormat; + "priority": number; + "stopIfTrue": boolean; + "textComparison": TextConditionalFormat; + "textComparisonOrNullObject": TextConditionalFormat; + "topBottom": TopBottomConditionalFormat; + "topBottomOrNullObject": TopBottomConditionalFormat; + "type": string; + }; + } + /** + * + * Represents an Excel Conditional Data Bar Type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class DataBarConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Representation of all values to the left of the axis in an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly negativeFormat: Excel.ConditionalDataBarNegativeFormat; + /** + * + * Representation of all values to the right of the axis in an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly positiveFormat: Excel.ConditionalDataBarPositiveFormat; + /** + * + * HTML color code representing the color of the Axis line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "" (empty string) if no axis is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + axisColor: string; + /** + * + * Representation of how the axis is determined for an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + axisFormat: string; + /** + * + * Represents the direction that the data bar graphic should be based on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + barDirection: string; + /** + * + * The rule for what consistutes the lower bound (and how to calculate it, if applicable) for a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + lowerBoundRule: Excel.ConditionalDataBarRule; + /** + * + * If true, hides the values from the cells where the data bar is applied. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + showDataBarOnly: boolean; + /** + * + * The rule for what constitutes the upper bound (and how to calculate it, if applicable) for a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + upperBoundRule: Excel.ConditionalDataBarRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DataBarConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: DataBarConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.DataBarConditionalFormat; + toJSON(): { + "axisColor": string; + "axisFormat": string; + "barDirection": string; + "lowerBoundRule": ConditionalDataBarRule; + "negativeFormat": ConditionalDataBarNegativeFormat; + "positiveFormat": ConditionalDataBarPositiveFormat; + "showDataBarOnly": boolean; + "upperBoundRule": ConditionalDataBarRule; + }; + } + /** + * + * Represents a conditional format DataBar Format for the positive side of the data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalDataBarPositiveFormat extends OfficeExtension.ClientObject { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "" (empty string) if no border is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + borderColor: string; + /** + * + * HTML color code representing the fill color, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + fillColor: string; + /** + * + * Boolean representation of whether or not the DataBar has a gradient. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + gradientFill: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalDataBarPositiveFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalDataBarPositiveFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalDataBarPositiveFormat; + toJSON(): { + "borderColor": string; + "fillColor": string; + "gradientFill": boolean; + }; + } + /** + * + * Represents a conditional format DataBar Format for the negative side of the data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalDataBarNegativeFormat extends OfficeExtension.ClientObject { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "Empty String" if no border is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + borderColor: string; + /** + * + * HTML color code representing the fill color, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + fillColor: string; + /** + * + * Boolean representation of whether or not the negative DataBar has the same border color as the positive DataBar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + matchPositiveBorderColor: boolean; + /** + * + * Boolean representation of whether or not the negative DataBar has the same fill color as the positive DataBar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + matchPositiveFillColor: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalDataBarNegativeFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalDataBarNegativeFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalDataBarNegativeFormat; + toJSON(): { + "borderColor": string; + "fillColor": string; + "matchPositiveBorderColor": boolean; + "matchPositiveFillColor": boolean; + }; + } + /** + * + * Represents a rule-type for a Data Bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalDataBarRule { + /** + * + * The formula, if required, to evaluate the databar rule on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula?: string; + /** + * + * The type of rule for the databar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + type: string; + } + /** + * + * Represents a custom conditional format type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class CustomConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly format: Excel.ConditionalRangeFormat; + /** + * + * Represents the Rule object on this conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly rule: Excel.ConditionalFormatRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.CustomConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: CustomConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.CustomConditionalFormat; + toJSON(): { + "format": ConditionalRangeFormat; + "rule": ConditionalFormatRule; + }; + } + /** + * + * Represents a rule, for all traditional rule/format pairings. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalFormatRule extends OfficeExtension.ClientObject { + /** + * + * The formula, if required, to evaluate the conditional format rule on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula: string; + /** + * + * The formula, if required, to evaluate the conditional format rule on in the user's language. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formulaLocal: string; + /** + * + * The formula, if required, to evaluate the conditional format rule on in R1C1-style notation. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formulaR1C1: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalFormatRuleUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalFormatRule): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalFormatRule; + toJSON(): { + "formula": string; + "formulaLocal": string; + "formulaR1C1": string; + }; + } + /** + * + * Represents an IconSet criteria for conditional formatting. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class IconSetConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * An array of Criteria and IconSets for the rules and potential custom icons for conditional icons. Note that for the first criterion only the custom icon can be modified, while type, formula and operator will be ignored when set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + criteria: Array; + /** + * + * If true, reverses the icon orders for the IconSet. Note that this cannot be set if custom icons are used. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + reverseIconOrder: boolean; + /** + * + * If true, hides the values and only shows icons. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + showIconOnly: boolean; + /** + * + * If set, displays the IconSet option for the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + style: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.IconSetConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: IconSetConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.IconSetConditionalFormat; + toJSON(): { + "criteria": ConditionalIconCriterion[]; + "reverseIconOrder": boolean; + "showIconOnly": boolean; + "style": string; + }; + } + /** + * + * Represents an Icon Criterion which contains a type, value, an Operator, and an optional custom icon, if not using an iconset. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalIconCriterion { + /** + * + * The custom icon for the current criterion if different from the default IconSet, else null will be returned. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + customIcon?: Excel.Icon; + /** + * + * A number or a formula depending on the type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula: string; + /** + * + * GreaterThan or GreaterThanOrEqual for each of the rule type for the Icon conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + operator: string; + /** + * + * What the icon conditional formula should be based on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + type: string; + } + /** + * + * Represents an IconSet criteria for conditional formatting. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ColorScaleConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * The criteria of the color scale. Midpoint is optional when using a two point color scale. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + criteria: Excel.ConditionalColorScaleCriteria; + /** + * + * If true the color scale will have three points (minimum, midpoint, maximum), otherwise it will have two (minimum, maximum). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly threeColorScale: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ColorScaleConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ColorScaleConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ColorScaleConditionalFormat; + toJSON(): { + "criteria": ConditionalColorScaleCriteria; + "threeColorScale": boolean; + }; + } + /** + * + * Represents the criteria of the color scale. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalColorScaleCriteria { + /** + * + * The maximum point Color Scale Criterion. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + maximum: Excel.ConditionalColorScaleCriterion; + /** + * + * The midpoint Color Scale Criterion if the color scale is a 3-color scale. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + midpoint?: Excel.ConditionalColorScaleCriterion; + /** + * + * The minimum point Color Scale Criterion. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + minimum: Excel.ConditionalColorScaleCriterion; + } + /** + * + * Represents a Color Scale Criterion which contains a type, value and a color. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalColorScaleCriterion { + /** + * + * HTML color code representation of the color scale color. E.g. #FF0000 represents Red. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color?: string; + /** + * + * A number, a formula, or null (if Type is LowestValue). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula?: string; + /** + * + * What the icon conditional formula should be based on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + type: string; + } + /** + * + * Represents a Top/Bottom conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class TopBottomConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly format: Excel.ConditionalRangeFormat; + /** + * + * The criteria of the Top/Bottom conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule: Excel.ConditionalTopBottomRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TopBottomConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TopBottomConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TopBottomConditionalFormat; + toJSON(): { + "format": ConditionalRangeFormat; + "rule": ConditionalTopBottomRule; + }; + } + /** + * + * Represents the rule of the top/bottom conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalTopBottomRule { + /** + * + * The rank between 1 and 1000 for numeric ranks or 1 and 100 for percent ranks. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rank: number; + /** + * + * Format values based on the top or bottom rank. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + type: string; + } + /** + * + * Represents the the preset criteria conditional format such as above average/below average/unique values/contains blank/nonblank/error/noerror. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class PresetCriteriaConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly format: Excel.ConditionalRangeFormat; + /** + * + * The rule of the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule: Excel.ConditionalPresetCriteriaRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.PresetCriteriaConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: PresetCriteriaConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PresetCriteriaConditionalFormat; + toJSON(): { + "format": ConditionalRangeFormat; + "rule": ConditionalPresetCriteriaRule; + }; + } + /** + * + * Represents the Preset Criteria Conditional Format Rule + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalPresetCriteriaRule { + /** + * + * The criterion of the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + criterion: string; + } + /** + * + * Represents a specific text conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class TextConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly format: Excel.ConditionalRangeFormat; + /** + * + * The rule of the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule: Excel.ConditionalTextComparisonRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TextConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TextConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TextConditionalFormat; + toJSON(): { + "format": ConditionalRangeFormat; + "rule": ConditionalTextComparisonRule; + }; + } + /** + * + * Represents a Cell Value Conditional Format Rule + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalTextComparisonRule { + /** + * + * The operator of the text conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + operator: string; + /** + * + * The Text value of conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + text: string; + } + /** + * + * Represents a cell value conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class CellValueConditionalFormat extends OfficeExtension.ClientObject { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly format: Excel.ConditionalRangeFormat; + /** + * + * Represents the Rule object on this conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule: Excel.ConditionalCellValueRule; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.CellValueConditionalFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: CellValueConditionalFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.CellValueConditionalFormat; + toJSON(): { + "format": ConditionalRangeFormat; + "rule": ConditionalCellValueRule; + }; + } + /** + * + * Represents a Cell Value Conditional Format Rule + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + interface ConditionalCellValueRule { + /** + * + * The formula, if required, to evaluate the conditional format rule on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula1: string; + /** + * + * The formula, if required, to evaluate the conditional format rule on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula2?: string; + /** + * + * The operator of the text conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + operator: string; + } + /** + * + * A format object encapsulating the conditional formats range's font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalRangeFormat extends OfficeExtension.ClientObject { + /** + * + * Collection of border objects that apply to the overall conditional format range. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly borders: Excel.ConditionalRangeBorderCollection; + /** + * + * Returns the fill object defined on the overall conditional format range. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly fill: Excel.ConditionalRangeFill; + /** + * + * Returns the font object defined on the overall conditional format range. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly font: Excel.ConditionalRangeFont; + /** + * + * Represents Excel's number format code for the given range. Cleared if null is passed in. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + numberFormat: any; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalRangeFormatUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalRangeFormat): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalRangeFormat; + toJSON(): { + "numberFormat": any; + }; + } + /** + * + * This object represents the font attributes (font style,, color, etc.) for an object. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalRangeFont extends OfficeExtension.ClientObject { + /** + * + * Represents the bold status of font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + bold: boolean; + /** + * + * HTML color code representation of the text color. E.g. #FF0000 represents Red. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color: string; + /** + * + * Represents the italic status of the font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + italic: boolean; + /** + * + * Represents the strikethrough status of the font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + strikethrough: boolean; + /** + * + * Type of underline applied to the font. See Excel.ConditionalRangeFontUnderlineStyle for details. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + underline: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalRangeFontUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalRangeFont): void; + /** + * + * Resets the font formats. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + clear(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalRangeFont; + toJSON(): { + "bold": boolean; + "color": string; + "italic": boolean; + "strikethrough": boolean; + "underline": string; + }; + } + /** + * + * Represents the background of a conditional range object. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalRangeFill extends OfficeExtension.ClientObject { + /** + * + * HTML color code representing the color of the fill, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalRangeFillUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalRangeFill): void; + /** + * + * Resets the fill. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + clear(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalRangeFill; + toJSON(): { + "color": string; + }; + } + /** + * + * Represents the border of an object. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalRangeBorder extends OfficeExtension.ClientObject { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color: string; + /** + * + * Constant value that indicates the specific side of the border. See Excel.ConditionalRangeBorderIndex for details. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly sideIndex: string; + /** + * + * One of the constants of line style specifying the line style for the border. See Excel.BorderLineStyle for details. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + style: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ConditionalRangeBorderUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ConditionalRangeBorder): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalRangeBorder; + toJSON(): { + "color": string; + "sideIndex": string; + "style": string; + }; + } + /** + * + * Represents the border objects that make up range border. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + class ConditionalRangeBorderCollection extends OfficeExtension.ClientObject { + /** + * + * Gets the top border + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly bottom: Excel.ConditionalRangeBorder; + /** + * + * Gets the top border + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly left: Excel.ConditionalRangeBorder; + /** + * + * Gets the top border + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly right: Excel.ConditionalRangeBorder; + /** + * + * Gets the top border + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly top: Excel.ConditionalRangeBorder; + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Number of border objects in the collection. Read-only. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + readonly count: number; + /** + * + * Gets a border object using its name + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + * + * @param index Index value of the border object to be retrieved. See Excel.ConditionalRangeBorderIndex for details. + */ + getItem(index: string): Excel.ConditionalRangeBorder; + /** + * + * Gets a border object using its index + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + * + * @param index Index value of the object to be retrieved. Zero-indexed. + */ + getItemAt(index: number): Excel.ConditionalRangeBorder; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ConditionalRangeBorderCollection; + toJSON(): { + "count": number; + }; + } /** * [Api set: ExcelApi 1.1] */ - module BindingType { + namespace BindingType { var range: string; var table: string; var text: string; @@ -6163,7 +8384,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module BorderIndex { + namespace BorderIndex { var edgeTop: string; var edgeBottom: string; var edgeLeft: string; @@ -6176,7 +8397,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module BorderLineStyle { + namespace BorderLineStyle { var none: string; var continuous: string; var dash: string; @@ -6189,7 +8410,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module BorderWeight { + namespace BorderWeight { var hairline: string; var thin: string; var medium: string; @@ -6198,7 +8419,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module CalculationMode { + namespace CalculationMode { var automatic: string; var automaticExceptTables: string; var manual: string; @@ -6206,23 +8427,39 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module CalculationType { + namespace CalculationType { + /** + * + * Recalculates all cells that Excel has marked as dirty, that is, dependents of volatile or changed data, and cells programmatically marked as dirty. + * + */ var recalculate: string; + /** + * + * This will mark all cells as dirty and then recalculate them. + * + */ var full: string; + /** + * + * This will rebuild the full dependency chain, mark all cells as dirty and then recalculate them. + * + */ var fullRebuild: string; } /** - * [Api set: ExcelApi 1.1] + * [Api set: ExcelApi 1.1 for All/Formats/Contents, 1.7 for Hyperlinks.] */ - module ClearApplyTo { + namespace ClearApplyTo { var all: string; var formats: string; var contents: string; + var hyperlinks: string; } /** * [Api set: ExcelApi 1.1] */ - module ChartDataLabelPosition { + namespace ChartDataLabelPosition { var invalid: string; var none: string; var center: string; @@ -6239,7 +8476,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module ChartLegendPosition { + namespace ChartLegendPosition { var invalid: string; var top: string; var bottom: string; @@ -6254,7 +8491,7 @@ declare module Excel { * * [Api set: ExcelApi 1.1] */ - module ChartSeriesBy { + namespace ChartSeriesBy { /** * * On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; on Excel Online, "auto" will simply default to "columns". @@ -6267,7 +8504,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module ChartType { + namespace ChartType { var invalid: string; var columnClustered: string; var columnStacked: string; @@ -6346,21 +8583,227 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module ChartUnderlineStyle { + namespace ChartUnderlineStyle { var none: string; var single: string; } + /** + * + * Represents the format options for a Data Bar Axis. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalDataBarAxisFormat { + var automatic: string; + var none: string; + var cellMidPoint: string; + } + /** + * + * Represents the Data Bar direction within a cell. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalDataBarDirection { + var context: string; + var leftToRight: string; + var rightToLeft: string; + } + /** + * + * Represents the direction for a selection. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatDirection { + var top: string; + var bottom: string; + } + /** + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatType { + var custom: string; + var dataBar: string; + var colorScale: string; + var iconSet: string; + var topBottom: string; + var presetCriteria: string; + var containsText: string; + var cellValue: string; + } + /** + * + * Represents the types of conditional format values. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatRuleType { + var invalid: string; + var automatic: string; + var lowestValue: string; + var highestValue: string; + var number: string; + var percent: string; + var formula: string; + var percentile: string; + } + /** + * + * Represents the types of conditional format values. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatIconRuleType { + var invalid: string; + var number: string; + var percent: string; + var formula: string; + var percentile: string; + } + /** + * + * Represents the types of conditional format values. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatColorCriterionType { + var invalid: string; + var lowestValue: string; + var highestValue: string; + var number: string; + var percent: string; + var formula: string; + var percentile: string; + } + /** + * + * Represents the criteria for the above/below average conditional format type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalTopBottomCriterionType { + var invalid: string; + var topItems: string; + var topPercent: string; + var bottomItems: string; + var bottomPercent: string; + } + /** + * + * Represents the criteria for the Preset Criteria conditional format type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalFormatPresetCriterion { + var invalid: string; + var blanks: string; + var nonBlanks: string; + var errors: string; + var nonErrors: string; + var yesterday: string; + var today: string; + var tomorrow: string; + var lastSevenDays: string; + var lastWeek: string; + var thisWeek: string; + var nextWeek: string; + var lastMonth: string; + var thisMonth: string; + var nextMonth: string; + var aboveAverage: string; + var belowAverage: string; + var equalOrAboveAverage: string; + var equalOrBelowAverage: string; + var oneStdDevAboveAverage: string; + var oneStdDevBelowAverage: string; + var twoStdDevAboveAverage: string; + var twoStdDevBelowAverage: string; + var threeStdDevAboveAverage: string; + var threeStdDevBelowAverage: string; + var uniqueValues: string; + var duplicateValues: string; + } + /** + * + * Represents the operator of the text conditional format type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalTextOperator { + var invalid: string; + var contains: string; + var notContains: string; + var beginsWith: string; + var endsWith: string; + } + /** + * + * Represents the operator of the text conditional format type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalCellValueOperator { + var invalid: string; + var between: string; + var notBetween: string; + var equalTo: string; + var notEqualTo: string; + var greaterThan: string; + var lessThan: string; + var greaterThanOrEqual: string; + var lessThanOrEqual: string; + } + /** + * + * Represents the operator for each icon criteria. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalIconCriterionOperator { + var invalid: string; + var greaterThan: string; + var greaterThanOrEqual: string; + } + /** + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalRangeBorderIndex { + var edgeTop: string; + var edgeBottom: string; + var edgeLeft: string; + var edgeRight: string; + } + /** + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalRangeBorderLineStyle { + var none: string; + var continuous: string; + var dash: string; + var dashDot: string; + var dashDotDot: string; + var dot: string; + } + /** + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + namespace ConditionalRangeFontUnderlineStyle { + var none: string; + var single: string; + var double: string; + } /** * [Api set: ExcelApi 1.1] */ - module DeleteShiftDirection { + namespace DeleteShiftDirection { var up: string; var left: string; } /** * [Api set: ExcelApi 1.2] */ - module DynamicFilterCriteria { + namespace DynamicFilterCriteria { var unknown: string; var aboveAverage: string; var allDatesInPeriodApril: string; @@ -6400,7 +8843,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module FilterDatetimeSpecificity { + namespace FilterDatetimeSpecificity { var year: string; var month: string; var day: string; @@ -6411,7 +8854,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module FilterOn { + namespace FilterOn { var bottomItems: string; var bottomPercent: string; var cellColor: string; @@ -6426,14 +8869,14 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module FilterOperator { + namespace FilterOperator { var and: string; var or: string; } /** * [Api set: ExcelApi 1.1] */ - module HorizontalAlignment { + namespace HorizontalAlignment { var general: string; var left: string; var center: string; @@ -6446,7 +8889,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module IconSet { + namespace IconSet { var invalid: string; var threeArrows: string; var threeArrowsGray: string; @@ -6472,7 +8915,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module ImageFittingMode { + namespace ImageFittingMode { var fit: string; var fitAndCenter: string; var fill: string; @@ -6480,14 +8923,21 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module InsertShiftDirection { + namespace InsertShiftDirection { var down: string; var right: string; } + /** + * [Api set: ExcelApi 1.4] + */ + namespace NamedItemScope { + var worksheet: string; + var workbook: string; + } /** * [Api set: ExcelApi 1.1] */ - module NamedItemType { + namespace NamedItemType { var string: string; var integer: string; var double: string; @@ -6498,7 +8948,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module RangeUnderlineStyle { + namespace RangeUnderlineStyle { var none: string; var single: string; var double: string; @@ -6508,7 +8958,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module SheetVisibility { + namespace SheetVisibility { var visible: string; var hidden: string; var veryHidden: string; @@ -6516,7 +8966,7 @@ declare module Excel { /** * [Api set: ExcelApi 1.1] */ - module RangeValueType { + namespace RangeValueType { var unknown: string; var empty: string; var string: string; @@ -6528,14 +8978,14 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module SortOrientation { + namespace SortOrientation { var rows: string; var columns: string; } /** * [Api set: ExcelApi 1.2] */ - module SortOn { + namespace SortOn { var value: string; var cellColor: string; var fontColor: string; @@ -6544,21 +8994,21 @@ declare module Excel { /** * [Api set: ExcelApi 1.2] */ - module SortDataOption { + namespace SortDataOption { var normal: string; var textAsNumber: string; } /** * [Api set: ExcelApi 1.2] */ - module SortMethod { + namespace SortMethod { var pinYin: string; var strokeCount: string; } /** * [Api set: ExcelApi 1.1] */ - module VerticalAlignment { + namespace VerticalAlignment { var top: string; var center: string; var bottom: string; @@ -6578,14 +9028,14 @@ declare module Excel { * * [Api set: ExcelApi 1.2] */ - error: string; + readonly error: string; /** * * The value of function evaluation. The value field will be populated only if no error has occurred (i.e., the Error property is not set). * * [Api set: ExcelApi 1.2] */ - value: T; + readonly value: T; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -6606,15 +9056,17 @@ declare module Excel { * * Returns the absolute value of a number, a number without its sign. * - * @param number Is the real number for which you want the absolute value. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the real number for which you want the absolute value. */ abs(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the accrued interest for a security that pays periodic interest. * + * [Api set: ExcelApi 1.2] + * * @param issue Is the security's issue date, expressed as a serial date number. * @param firstInterest Is the security's first interest date, expressed as a serial date number. * @param settlement Is the security's settlement date, expressed as a serial date number. @@ -6623,63 +9075,63 @@ declare module Excel { * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. * @param calcMethod Is a logical value: to accrued interest from issue date = TRUE or omitted; to calculate from last coupon payment date = FALSE. - * - * [Api set: ExcelApi 1.2] */ accrInt(issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, firstInterest: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, par: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, calcMethod?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the accrued interest for a security that pays interest at maturity. * + * [Api set: ExcelApi 1.2] + * * @param issue Is the security's issue date, expressed as a serial date number. * @param settlement Is the security's maturity date, expressed as a serial date number. * @param rate Is the security's annual coupon rate. * @param par Is the security's par value. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ accrIntM(issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, par: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the arccosine of a number, in radians in the range 0 to Pi. The arccosine is the angle whose cosine is Number. * - * @param number Is the cosine of the angle you want and must be from -1 to 1. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the cosine of the angle you want and must be from -1 to 1. */ acos(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse hyperbolic cosine of a number. * - * @param number Is any real number equal to or greater than 1. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number equal to or greater than 1. */ acosh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the arccotangent of a number, in radians in the range 0 to Pi. * - * @param number Is the cotangent of the angle you want. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the cotangent of the angle you want. */ acot(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse hyperbolic cotangent of a number. * - * @param number Is the hyperbolic cotangent of the angle that you want. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the hyperbolic cotangent of the angle that you want. */ acoth(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the prorated linear depreciation of an asset for each accounting period. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the cost of the asset. * @param datePurchased Is the date the asset is purchased. * @param firstPeriod Is the date of the end of the first period. @@ -6687,14 +9139,14 @@ declare module Excel { * @param period Is the period. * @param rate Is the rate of depreciation. * @param basis Year_basis : 0 for year of 360 days, 1 for actual, 3 for year of 365 days. - * - * [Api set: ExcelApi 1.2] */ amorDegrc(cost: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, datePurchased: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, firstPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, period: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the prorated linear depreciation of an asset for each accounting period. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the cost of the asset. * @param datePurchased Is the date the asset is purchased. * @param firstPeriod Is the date of the end of the first period. @@ -6702,1260 +9154,1258 @@ declare module Excel { * @param period Is the period. * @param rate Is the rate of depreciation. * @param basis Year_basis : 0 for year of 360 days, 1 for actual, 3 for year of 365 days. - * - * [Api set: ExcelApi 1.2] */ amorLinc(cost: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, datePurchased: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, firstPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, period: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether all arguments are TRUE, and returns TRUE if all arguments are TRUE. * - * @param values List of parameters, whose elements are 1 to 255 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references. */ and(...values: Array>): FunctionResult; /** * * Converts a Roman numeral to Arabic. * - * @param text Is the Roman numeral you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the Roman numeral you want to convert. */ arabic(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of areas in a reference. An area is a range of contiguous cells or a single cell. * - * @param reference Is a reference to a cell or range of cells and can refer to multiple areas. - * * [Api set: ExcelApi 1.2] + * + * @param reference Is a reference to a cell or range of cells and can refer to multiple areas. */ areas(reference: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Changes full-width (double-byte) characters to half-width (single-byte) characters. Use with double-byte character sets (DBCS). * - * @param text Is a text, or a reference to a cell containing a text. - * * [Api set: ExcelApi 1.2] + * + * @param text Is a text, or a reference to a cell containing a text. */ asc(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the arcsine of a number in radians, in the range -Pi/2 to Pi/2. * - * @param number Is the sine of the angle you want and must be from -1 to 1. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the sine of the angle you want and must be from -1 to 1. */ asin(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse hyperbolic sine of a number. * - * @param number Is any real number equal to or greater than 1. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number equal to or greater than 1. */ asinh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the arctangent of a number in radians, in the range -Pi/2 to Pi/2. * - * @param number Is the tangent of the angle you want. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the tangent of the angle you want. */ atan(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the arctangent of the specified x- and y- coordinates, in radians between -Pi and Pi, excluding -Pi. * + * [Api set: ExcelApi 1.2] + * * @param xNum Is the x-coordinate of the point. * @param yNum Is the y-coordinate of the point. - * - * [Api set: ExcelApi 1.2] */ atan2(xNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse hyperbolic tangent of a number. * - * @param number Is any real number between -1 and 1 excluding -1 and 1. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number between -1 and 1 excluding -1 and 1. */ atanh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the average of the absolute deviations of data points from their mean. Arguments can be numbers or names, arrays, or references that contain numbers. * - * @param values List of parameters, whose elements are 1 to 255 arguments for which you want the average of the absolute deviations. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 arguments for which you want the average of the absolute deviations. */ aveDev(...values: Array>): FunctionResult; /** * * Returns the average (arithmetic mean) of its arguments, which can be numbers or names, arrays, or references that contain numbers. * - * @param values List of parameters, whose elements are 1 to 255 numeric arguments for which you want the average. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numeric arguments for which you want the average. */ average(...values: Array>): FunctionResult; /** * * Returns the average (arithmetic mean) of its arguments, evaluating text and FALSE in arguments as 0; TRUE evaluates as 1. Arguments can be numbers, names, arrays, or references. * - * @param values List of parameters, whose elements are 1 to 255 arguments for which you want the average. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 arguments for which you want the average. */ averageA(...values: Array>): FunctionResult; /** * * Finds average(arithmetic mean) for the cells specified by a given condition or criteria. * + * [Api set: ExcelApi 1.2] + * * @param range Is the range of cells you want evaluated. * @param criteria Is the condition or criteria in the form of a number, expression, or text that defines which cells will be used to find the average. * @param averageRange Are the actual cells to be used to find the average. If omitted, the cells in range are used. - * - * [Api set: ExcelApi 1.2] */ averageIf(range: Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, averageRange?: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Finds average(arithmetic mean) for the cells specified by a given set of conditions or criteria. * + * [Api set: ExcelApi 1.2] + * * @param averageRange Are the actual cells to be used to find the average. * @param values List of parameters, where the first element of each pair is the Is the range of cells you want evaluated for the particular condition , and the second element is is the condition or criteria in the form of a number, expression, or text that defines which cells will be used to find the average. - * - * [Api set: ExcelApi 1.2] */ averageIfs(averageRange: Excel.Range | Excel.RangeReference | Excel.FunctionResult, ...values: Array | number | string | boolean>): FunctionResult; /** * * Converts a number to text (baht). * - * @param number Is a number that you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param number Is a number that you want to convert. */ bahtText(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a number into a text representation with the given radix (base). * + * [Api set: ExcelApi 1.2] + * * @param number Is the number that you want to convert. * @param radix Is the base Radix that you want to convert the number into. * @param minLength Is the minimum length of the returned string. If omitted leading zeros are not added. - * - * [Api set: ExcelApi 1.2] */ base(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, radix: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, minLength?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the modified Bessel function In(x). * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function. * @param n Is the order of the Bessel function. - * - * [Api set: ExcelApi 1.2] */ besselI(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, n: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Bessel function Jn(x). * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function. * @param n Is the order of the Bessel function. - * - * [Api set: ExcelApi 1.2] */ besselJ(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, n: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the modified Bessel function Kn(x). * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function. * @param n Is the order of the function. - * - * [Api set: ExcelApi 1.2] */ besselK(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, n: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Bessel function Yn(x). * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function. * @param n Is the order of the function. - * - * [Api set: ExcelApi 1.2] */ besselY(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, n: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the beta probability distribution function. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value between A and B at which to evaluate the function. * @param alpha Is a parameter to the distribution and must be greater than 0. * @param beta Is a parameter to the distribution and must be greater than 0. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. * @param A Is an optional lower bound to the interval of x. If omitted, A = 0. * @param B Is an optional upper bound to the interval of x. If omitted, B = 1. - * - * [Api set: ExcelApi 1.2] */ beta_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, beta: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, A?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, B?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the cumulative beta probability density function (BETA.DIST). * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the beta distribution. * @param alpha Is a parameter to the distribution and must be greater than 0. * @param beta Is a parameter to the distribution and must be greater than 0. * @param A Is an optional lower bound to the interval of x. If omitted, A = 0. * @param B Is an optional upper bound to the interval of x. If omitted, B = 1. - * - * [Api set: ExcelApi 1.2] */ beta_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, beta: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, A?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, B?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a binary number to decimal. * - * @param number Is the binary number you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the binary number you want to convert. */ bin2Dec(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a binary number to hexadecimal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the binary number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ bin2Hex(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a binary number to octal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the binary number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ bin2Oct(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the individual term binomial distribution probability. * + * [Api set: ExcelApi 1.2] + * * @param numberS Is the number of successes in trials. * @param trials Is the number of independent trials. * @param probabilityS Is the probability of success on each trial. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ binom_Dist(numberS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, trials: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, probabilityS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the probability of a trial result using a binomial distribution. * + * [Api set: ExcelApi 1.2] + * * @param trials Is the number of independent trials. * @param probabilityS Is the probability of success on each trial. * @param numberS Is the number of successes in trials. * @param numberS2 If provided this function returns the probability that the number of successful trials shall lie between numberS and numberS2. - * - * [Api set: ExcelApi 1.2] */ binom_Dist_Range(trials: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, probabilityS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberS2?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the smallest value for which the cumulative binomial distribution is greater than or equal to a criterion value. * + * [Api set: ExcelApi 1.2] + * * @param trials Is the number of Bernoulli trials. * @param probabilityS Is the probability of success on each trial, a number between 0 and 1 inclusive. * @param alpha Is the criterion value, a number between 0 and 1 inclusive. - * - * [Api set: ExcelApi 1.2] */ binom_Inv(trials: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, probabilityS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a bitwise 'And' of two numbers. * + * [Api set: ExcelApi 1.2] + * * @param number1 Is the decimal representation of the binary number you want to evaluate. * @param number2 Is the decimal representation of the binary number you want to evaluate. - * - * [Api set: ExcelApi 1.2] */ bitand(number1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, number2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a number shifted left by shift_amount bits. * + * [Api set: ExcelApi 1.2] + * * @param number Is the decimal representation of the binary number you want to evaluate. * @param shiftAmount Is the number of bits that you want to shift Number left by. - * - * [Api set: ExcelApi 1.2] */ bitlshift(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, shiftAmount: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a bitwise 'Or' of two numbers. * + * [Api set: ExcelApi 1.2] + * * @param number1 Is the decimal representation of the binary number you want to evaluate. * @param number2 Is the decimal representation of the binary number you want to evaluate. - * - * [Api set: ExcelApi 1.2] */ bitor(number1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, number2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a number shifted right by shift_amount bits. * + * [Api set: ExcelApi 1.2] + * * @param number Is the decimal representation of the binary number you want to evaluate. * @param shiftAmount Is the number of bits that you want to shift Number right by. - * - * [Api set: ExcelApi 1.2] */ bitrshift(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, shiftAmount: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a bitwise 'Exclusive Or' of two numbers. * + * [Api set: ExcelApi 1.2] + * * @param number1 Is the decimal representation of the binary number you want to evaluate. * @param number2 Is the decimal representation of the binary number you want to evaluate. - * - * [Api set: ExcelApi 1.2] */ bitxor(number1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, number2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number up, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value you want to round. * @param significance Is the multiple to which you want to round. * @param mode When given and nonzero this function will round away from zero. - * - * [Api set: ExcelApi 1.2] */ ceiling_Math(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mode?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number up, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value you want to round. * @param significance Is the multiple to which you want to round. - * - * [Api set: ExcelApi 1.2] */ ceiling_Precise(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the character specified by the code number from the character set for your computer. * - * @param number Is a number between 1 and 255 specifying which character you want. - * * [Api set: ExcelApi 1.2] + * + * @param number Is a number between 1 and 255 specifying which character you want. */ char(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the left-tailed probability of the chi-squared distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which you want to evaluate the distribution, a nonnegative number. * @param degFreedom Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param cumulative Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE. - * - * [Api set: ExcelApi 1.2] */ chiSq_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the right-tailed probability of the chi-squared distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which you want to evaluate the distribution, a nonnegative number. * @param degFreedom Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ chiSq_Dist_RT(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the left-tailed probability of the chi-squared distribution. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the chi-squared distribution, a value between 0 and 1 inclusive. * @param degFreedom Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ chiSq_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the right-tailed probability of the chi-squared distribution. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the chi-squared distribution, a value between 0 and 1 inclusive. * @param degFreedom Is the number of degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ chiSq_Inv_RT(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Chooses a value or action to perform from a list of values, based on an index number. * + * [Api set: ExcelApi 1.2] + * * @param indexNum Specifies which value argument is selected. indexNum must be between 1 and 254, or a formula or a reference to a number between 1 and 254. * @param values List of parameters, whose elements are 1 to 254 numbers, cell references, defined names, formulas, functions, or text arguments from which CHOOSE selects. - * - * [Api set: ExcelApi 1.2] */ choose(indexNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, ...values: Array>): FunctionResult; /** * * Removes all nonprintable characters from text. * - * @param text Is any worksheet information from which you want to remove nonprintable characters. - * * [Api set: ExcelApi 1.2] + * + * @param text Is any worksheet information from which you want to remove nonprintable characters. */ clean(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a numeric code for the first character in a text string, in the character set used by your computer. * - * @param text Is the text for which you want the code of the first character. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text for which you want the code of the first character. */ code(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of columns in an array or reference. * - * @param array Is an array or array formula, or a reference to a range of cells for which you want the number of columns. - * * [Api set: ExcelApi 1.2] + * + * @param array Is an array or array formula, or a reference to a range of cells for which you want the number of columns. */ columns(array: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of combinations for a given number of items. * + * [Api set: ExcelApi 1.2] + * * @param number Is the total number of items. * @param numberChosen Is the number of items in each combination. - * - * [Api set: ExcelApi 1.2] */ combin(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberChosen: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of combinations with repetitions for a given number of items. * + * [Api set: ExcelApi 1.2] + * * @param number Is the total number of items. * @param numberChosen Is the number of items in each combination. - * - * [Api set: ExcelApi 1.2] */ combina(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberChosen: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts real and imaginary coefficients into a complex number. * + * [Api set: ExcelApi 1.2] + * * @param realNum Is the real coefficient of the complex number. * @param iNum Is the imaginary coefficient of the complex number. * @param suffix Is the suffix for the imaginary component of the complex number. - * - * [Api set: ExcelApi 1.2] */ complex(realNum: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, iNum: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, suffix?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Joins several text strings into one text string. * - * @param values List of parameters, whose elements are 1 to 255 text strings to be joined into a single text string and can be text strings, numbers, or single-cell references. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 text strings to be joined into a single text string and can be text strings, numbers, or single-cell references. */ concatenate(...values: Array>): FunctionResult; /** * * Returns the confidence interval for a population mean, using a normal distribution. * + * [Api set: ExcelApi 1.2] + * * @param alpha Is the significance level used to compute the confidence level, a number greater than 0 and less than 1. * @param standardDev Is the population standard deviation for the data range and is assumed to be known. standardDev must be greater than 0. * @param size Is the sample size. - * - * [Api set: ExcelApi 1.2] */ confidence_Norm(alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, size: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the confidence interval for a population mean, using a Student's T distribution. * + * [Api set: ExcelApi 1.2] + * * @param alpha Is the significance level used to compute the confidence level, a number greater than 0 and less than 1. * @param standardDev Is the population standard deviation for the data range and is assumed to be known. standardDev must be greater than 0. * @param size Is the sample size. - * - * [Api set: ExcelApi 1.2] */ confidence_T(alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, size: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a number from one measurement system to another. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value in from_units to convert. * @param fromUnit Is the units for number. * @param toUnit Is the units for the result. - * - * [Api set: ExcelApi 1.2] */ convert(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fromUnit: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, toUnit: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cosine of an angle. * - * @param number Is the angle in radians for which you want the cosine. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the cosine. */ cos(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic cosine of a number. * - * @param number Is any real number. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number. */ cosh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cotangent of an angle. * - * @param number Is the angle in radians for which you want the cotangent. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the cotangent. */ cot(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic cotangent of a number. * - * @param number Is the angle in radians for which you want the hyperbolic cotangent. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the hyperbolic cotangent. */ coth(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Counts the number of cells in a range that contain numbers. * - * @param values List of parameters, whose elements are 1 to 255 arguments that can contain or refer to a variety of different types of data, but only numbers are counted. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 arguments that can contain or refer to a variety of different types of data, but only numbers are counted. */ count(...values: Array>): FunctionResult; /** * * Counts the number of cells in a range that are not empty. * - * @param values List of parameters, whose elements are 1 to 255 arguments representing the values and cells you want to count. Values can be any type of information. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 arguments representing the values and cells you want to count. Values can be any type of information. */ countA(...values: Array>): FunctionResult; /** * * Counts the number of empty cells in a specified range of cells. * - * @param range Is the range from which you want to count the empty cells. - * * [Api set: ExcelApi 1.2] + * + * @param range Is the range from which you want to count the empty cells. */ countBlank(range: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Counts the number of cells within a range that meet the given condition. * + * [Api set: ExcelApi 1.2] + * * @param range Is the range of cells from which you want to count nonblank cells. * @param criteria Is the condition in the form of a number, expression, or text that defines which cells will be counted. - * - * [Api set: ExcelApi 1.2] */ countIf(range: Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Counts the number of cells specified by a given set of conditions or criteria. * - * @param values List of parameters, where the first element of each pair is the Is the range of cells you want evaluated for the particular condition , and the second element is is the condition in the form of a number, expression, or text that defines which cells will be counted. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, where the first element of each pair is the Is the range of cells you want evaluated for the particular condition , and the second element is is the condition in the form of a number, expression, or text that defines which cells will be counted. */ countIfs(...values: Array | number | string | boolean>): FunctionResult; /** * * Returns the number of days from the beginning of the coupon period to the settlement date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupDayBs(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of days in the coupon period that contains the settlement date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupDays(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of days from the settlement date to the next coupon date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupDaysNc(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the next coupon date after the settlement date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupNcd(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of coupons payable between the settlement date and maturity date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupNum(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the previous coupon date before the settlement date. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ coupPcd(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cosecant of an angle. * - * @param number Is the angle in radians for which you want the cosecant. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the cosecant. */ csc(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic cosecant of an angle. * - * @param number Is the angle in radians for which you want the hyperbolic cosecant. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the hyperbolic cosecant. */ csch(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cumulative interest paid between two periods. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate. * @param nper Is the total number of payment periods. * @param pv Is the present value. * @param startPeriod Is the first period in the calculation. * @param endPeriod Is the last period in the calculation. * @param type Is the timing of the payment. - * - * [Api set: ExcelApi 1.2] */ cumIPmt(rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cumulative principal paid on a loan between two periods. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate. * @param nper Is the total number of payment periods. * @param pv Is the present value. * @param startPeriod Is the first period in the calculation. * @param endPeriod Is the last period in the calculation. * @param type Is the timing of the payment. - * - * [Api set: ExcelApi 1.2] */ cumPrinc(rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endPeriod: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Averages the values in a column in a list or database that match conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ daverage(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Counts the cells containing numbers in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dcount(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Counts nonblank cells in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dcountA(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Extracts from a database a single record that matches the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dget(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the largest number in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dmax(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the smallest number in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dmin(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Multiplies the values in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dproduct(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Estimates the standard deviation based on a sample from selected database entries. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dstDev(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Calculates the standard deviation based on the entire population of selected database entries. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dstDevP(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Adds the numbers in the field (column) of records in the database that match the conditions you specify. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dsum(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Estimates variance based on a sample from selected database entries. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dvar(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Calculates variance based on the entire population of selected database entries. * + * [Api set: ExcelApi 1.2] + * * @param database Is the range of cells that makes up the list or database. A database is a list of related data. * @param field Is either the label of the column in double quotation marks or a number that represents the column's position in the list. * @param criteria Is the range of cells that contains the conditions you specify. The range includes a column label and one cell below the label for a condition. - * - * [Api set: ExcelApi 1.2] */ dvarP(database: Excel.Range | Excel.RangeReference | Excel.FunctionResult, field: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number that represents the date in Microsoft Excel date-time code. * + * [Api set: ExcelApi 1.2] + * * @param year Is a number from 1900 or 1904 (depending on the workbook's date system) to 9999. * @param month Is a number from 1 to 12 representing the month of the year. * @param day Is a number from 1 to 31 representing the day of the month. - * - * [Api set: ExcelApi 1.2] */ date(year: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, month: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, day: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a date in the form of text to a number that represents the date in Microsoft Excel date-time code. * - * @param dateText Is text that represents a date in a Microsoft Excel date format, between 1/1/1900 or 1/1/1904 (depending on the workbook's date system) and 12/31/9999. - * * [Api set: ExcelApi 1.2] + * + * @param dateText Is text that represents a date in a Microsoft Excel date format, between 1/1/1900 or 1/1/1904 (depending on the workbook's date system) and 12/31/9999. */ datevalue(dateText: string | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the day of the month, a number from 1 to 31. * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel. */ day(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of days between the two dates. * + * [Api set: ExcelApi 1.2] + * * @param endDate startDate and endDate are the two dates between which you want to know the number of days. * @param startDate startDate and endDate are the two dates between which you want to know the number of days. - * - * [Api set: ExcelApi 1.2] */ days(endDate: string | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startDate: string | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of days between two dates based on a 360-day year (twelve 30-day months). * + * [Api set: ExcelApi 1.2] + * * @param startDate startDate and endDate are the two dates between which you want to know the number of days. * @param endDate startDate and endDate are the two dates between which you want to know the number of days. * @param method Is a logical value specifying the calculation method: U.S. (NASD) = FALSE or omitted; European = TRUE. - * - * [Api set: ExcelApi 1.2] */ days360(startDate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endDate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, method?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the depreciation of an asset for a specified period using the fixed-declining balance method. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the initial cost of the asset. * @param salvage Is the salvage value at the end of the life of the asset. * @param life Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset). * @param period Is the period for which you want to calculate the depreciation. Period must use the same units as Life. * @param month Is the number of months in the first year. If month is omitted, it is assumed to be 12. - * - * [Api set: ExcelApi 1.2] */ db(cost: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, life: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, period: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, month?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Changes half-width (single-byte) characters within a character string to full-width (double-byte) characters. Use with double-byte character sets (DBCS). * - * @param text Is a text, or a reference to a cell containing a text. - * * [Api set: ExcelApi 1.2] + * + * @param text Is a text, or a reference to a cell containing a text. */ dbcs(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the depreciation of an asset for a specified period using the double-declining balance method or some other method you specify. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the initial cost of the asset. * @param salvage Is the salvage value at the end of the life of the asset. * @param life Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset). * @param period Is the period for which you want to calculate the depreciation. Period must use the same units as Life. * @param factor Is the rate at which the balance declines. If Factor is omitted, it is assumed to be 2 (the double-declining balance method). - * - * [Api set: ExcelApi 1.2] */ ddb(cost: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, life: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, period: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, factor?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a decimal number to binary. * + * [Api set: ExcelApi 1.2] + * * @param number Is the decimal integer you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ dec2Bin(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a decimal number to hexadecimal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the decimal integer you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ dec2Hex(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a decimal number to octal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the decimal integer you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ dec2Oct(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a text representation of a number in a given base into a decimal number. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number that you want to convert. * @param radix Is the base Radix of the number you are converting. - * - * [Api set: ExcelApi 1.2] */ decimal(number: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, radix: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts radians to degrees. * - * @param angle Is the angle in radians that you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param angle Is the angle in radians that you want to convert. */ degrees(angle: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Tests whether two numbers are equal. * + * [Api set: ExcelApi 1.2] + * * @param number1 Is the first number. * @param number2 Is the second number. - * - * [Api set: ExcelApi 1.2] */ delta(number1: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, number2?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sum of squares of deviations of data points from their sample mean. * - * @param values List of parameters, whose elements are 1 to 255 arguments, or an array or array reference, on which you want DEVSQ to calculate. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 arguments, or an array or array reference, on which you want DEVSQ to calculate. */ devSq(...values: Array>): FunctionResult; /** * * Returns the discount rate for a security. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param pr Is the security's price per $100 face value. * @param redemption Is the security's redemption value per $100 face value. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ disc(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a number to text, using currency format. * + * [Api set: ExcelApi 1.2] + * * @param number Is a number, a reference to a cell containing a number, or a formula that evaluates to a number. * @param decimals Is the number of digits to the right of the decimal point. The number is rounded as necessary; if omitted, Decimals = 2. - * - * [Api set: ExcelApi 1.2] */ dollar(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, decimals?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a dollar price, expressed as a fraction, into a dollar price, expressed as a decimal number. * + * [Api set: ExcelApi 1.2] + * * @param fractionalDollar Is a number expressed as a fraction. * @param fraction Is the integer to use in the denominator of the fraction. - * - * [Api set: ExcelApi 1.2] */ dollarDe(fractionalDollar: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fraction: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a dollar price, expressed as a decimal number, into a dollar price, expressed as a fraction. * + * [Api set: ExcelApi 1.2] + * * @param decimalDollar Is a decimal number. * @param fraction Is the integer to use in the denominator of a fraction. - * - * [Api set: ExcelApi 1.2] */ dollarFr(decimalDollar: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fraction: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the annual duration of a security with periodic interest payments. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param coupon Is the security's annual coupon rate. * @param yld Is the security's annual yield. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ duration(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, coupon: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number up, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value you want to round. * @param significance Is the multiple to which you want to round. - * - * [Api set: ExcelApi 1.2] */ ecma_Ceiling(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the serial number of the date that is the indicated number of months before or after the start date. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param months Is the number of months before or after startDate. - * - * [Api set: ExcelApi 1.2] */ edate(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, months: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the effective annual interest rate. * + * [Api set: ExcelApi 1.2] + * * @param nominalRate Is the nominal interest rate. * @param npery Is the number of compounding periods per year. - * - * [Api set: ExcelApi 1.2] */ effect(nominalRate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, npery: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the serial number of the last day of the month before or after a specified number of months. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param months Is the number of months before or after the startDate. - * - * [Api set: ExcelApi 1.2] */ eoMonth(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, months: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the error function. * + * [Api set: ExcelApi 1.2] + * * @param lowerLimit Is the lower bound for integrating ERF. * @param upperLimit Is the upper bound for integrating ERF. - * - * [Api set: ExcelApi 1.2] */ erf(lowerLimit: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, upperLimit?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the complementary error function. * - * @param x Is the lower bound for integrating ERF. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the lower bound for integrating ERF. */ erfC(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the complementary error function. * - * @param X Is the lower bound for integrating ERFC.PRECISE. - * * [Api set: ExcelApi 1.2] + * + * @param X Is the lower bound for integrating ERFC.PRECISE. */ erfC_Precise(X: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the error function. * - * @param X Is the lower bound for integrating ERF.PRECISE. - * * [Api set: ExcelApi 1.2] + * + * @param X Is the lower bound for integrating ERF.PRECISE. */ erf_Precise(X: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a number matching an error value. * - * @param errorVal Is the error value for which you want the identifying number, and can be an actual error value or a reference to a cell containing an error value. - * * [Api set: ExcelApi 1.2] + * + * @param errorVal Is the error value for which you want the identifying number, and can be an actual error value or a reference to a cell containing an error value. */ error_Type(errorVal: string | number | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a positive number up and negative number down to the nearest even integer. * - * @param number Is the value to round. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the value to round. */ even(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether two text strings are exactly the same, and returns TRUE or FALSE. EXACT is case-sensitive. * + * [Api set: ExcelApi 1.2] + * * @param text1 Is the first text string. * @param text2 Is the second text string. - * - * [Api set: ExcelApi 1.2] */ exact(text1: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, text2: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns e raised to the power of a given number. * - * @param number Is the exponent applied to the base e. The constant e equals 2.71828182845904, the base of the natural logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the exponent applied to the base e. The constant e equals 2.71828182845904, the base of the natural logarithm. */ exp(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the exponential distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value of the function, a nonnegative number. * @param lambda Is the parameter value, a positive number. * @param cumulative Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE. - * - * [Api set: ExcelApi 1.2] */ expon_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, lambda: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the future value of an initial principal after applying a series of compound interest rates. * + * [Api set: ExcelApi 1.2] + * * @param principal Is the present value. * @param schedule Is an array of interest rates to apply. - * - * [Api set: ExcelApi 1.2] */ fvschedule(principal: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, schedule: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the (left-tailed) F probability distribution (degree of diversity) for two data sets. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function, a nonnegative number. * @param degFreedom1 Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param degFreedom2 Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param cumulative Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE. - * - * [Api set: ExcelApi 1.2] */ f_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the (right-tailed) F probability distribution (degree of diversity) for two data sets. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function, a nonnegative number. * @param degFreedom1 Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param degFreedom2 Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ f_Dist_RT(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the (left-tailed) F probability distribution: if p = F.DIST(x,...), then F.INV(p,...) = x. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the F cumulative distribution, a number between 0 and 1 inclusive. * @param degFreedom1 Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param degFreedom2 Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ f_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the (right-tailed) F probability distribution: if p = F.DIST.RT(x,...), then F.INV.RT(p,...) = x. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the F cumulative distribution, a number between 0 and 1 inclusive. * @param degFreedom1 Is the numerator degrees of freedom, a number between 1 and 10^10, excluding 10^10. * @param degFreedom2 Is the denominator degrees of freedom, a number between 1 and 10^10, excluding 10^10. - * - * [Api set: ExcelApi 1.2] */ f_Inv_RT(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom1: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom2: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the factorial of a number, equal to 1*2*3*...* Number. * - * @param number Is the nonnegative number you want the factorial of. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the nonnegative number you want the factorial of. */ fact(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the double factorial of a number. * - * @param number Is the value for which to return the double factorial. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the value for which to return the double factorial. */ factDouble(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -7969,978 +10419,978 @@ declare module Excel { * * Returns the starting position of one text string within another text string. FIND is case-sensitive. * + * [Api set: ExcelApi 1.2] + * * @param findText Is the text you want to find. Use double quotes (empty text) to match the first character in withinText; wildcard characters not allowed. * @param withinText Is the text containing the text you want to find. * @param startNum Specifies the character at which to start the search. The first character in withinText is character number 1. If omitted, startNum = 1. - * - * [Api set: ExcelApi 1.2] */ find(findText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, withinText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Finds the starting position of one text string within another text string. FINDB is case-sensitive. Use with double-byte character sets (DBCS). * + * [Api set: ExcelApi 1.2] + * * @param findText Is the text you want to find. * @param withinText Is the text containing the text you want to find. * @param startNum Specifies the character at which to start the search. - * - * [Api set: ExcelApi 1.2] */ findB(findText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, withinText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Fisher transformation. * - * @param x Is the value for which you want the transformation, a number between -1 and 1, excluding -1 and 1. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the value for which you want the transformation, a number between -1 and 1, excluding -1 and 1. */ fisher(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the Fisher transformation: if y = FISHER(x), then FISHERINV(y) = x. * - * @param y Is the value for which you want to perform the inverse of the transformation. - * * [Api set: ExcelApi 1.2] + * + * @param y Is the value for which you want to perform the inverse of the transformation. */ fisherInv(y: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number to the specified number of decimals and returns the result as text with or without commas. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number you want to round and convert to text. * @param decimals Is the number of digits to the right of the decimal point. If omitted, Decimals = 2. * @param noCommas Is a logical value: do not display commas in the returned text = TRUE; do display commas in the returned text = FALSE or omitted. - * - * [Api set: ExcelApi 1.2] */ fixed(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, decimals?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, noCommas?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number down, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value you want to round. * @param significance Is the multiple to which you want to round. * @param mode When given and nonzero this function will round towards zero. - * - * [Api set: ExcelApi 1.2] */ floor_Math(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mode?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number down, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the numeric value you want to round. * @param significance Is the multiple to which you want to round. - * - * [Api set: ExcelApi 1.2] */ floor_Precise(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the future value of an investment based on periodic, constant payments and a constant interest rate. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param nper Is the total number of payment periods in the investment. * @param pmt Is the payment made each period; it cannot change over the life of the investment. * @param pv Is the present value, or the lump-sum amount that a series of future payments is worth now. If omitted, Pv = 0. * @param type Is a value representing the timing of payment: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. - * - * [Api set: ExcelApi 1.2] */ fv(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pmt: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Gamma function value. * - * @param x Is the value for which you want to calculate Gamma. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the value for which you want to calculate Gamma. */ gamma(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the natural logarithm of the gamma function. * - * @param x Is the value for which you want to calculate GAMMALN, a positive number. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the value for which you want to calculate GAMMALN, a positive number. */ gammaLn(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the natural logarithm of the gamma function. * - * @param x Is the value for which you want to calculate GAMMALN.PRECISE, a positive number. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the value for which you want to calculate GAMMALN.PRECISE, a positive number. */ gammaLn_Precise(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the gamma distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which you want to evaluate the distribution, a nonnegative number. * @param alpha Is a parameter to the distribution, a positive number. * @param beta Is a parameter to the distribution, a positive number. If beta = 1, GAMMA.DIST returns the standard gamma distribution. * @param cumulative Is a logical value: return the cumulative distribution function = TRUE; return the probability mass function = FALSE or omitted. - * - * [Api set: ExcelApi 1.2] */ gamma_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, beta: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the gamma cumulative distribution: if p = GAMMA.DIST(x,...), then GAMMA.INV(p,...) = x. * + * [Api set: ExcelApi 1.2] + * * @param probability Is the probability associated with the gamma distribution, a number between 0 and 1, inclusive. * @param alpha Is a parameter to the distribution, a positive number. * @param beta Is a parameter to the distribution, a positive number. If beta = 1, GAMMA.INV returns the inverse of the standard gamma distribution. - * - * [Api set: ExcelApi 1.2] */ gamma_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, beta: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns 0.5 less than the standard normal cumulative distribution. * - * @param x Is the value for which you want the distribution. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the value for which you want the distribution. */ gauss(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the greatest common divisor. * - * @param values List of parameters, whose elements are 1 to 255 values. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 values. */ gcd(...values: Array>): FunctionResult; /** * * Tests whether a number is greater than a threshold value. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value to test against step. * @param step Is the threshold value. - * - * [Api set: ExcelApi 1.2] */ geStep(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, step?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the geometric mean of an array or range of positive numeric data. * - * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the mean. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the mean. */ geoMean(...values: Array>): FunctionResult; /** * * Looks for a value in the top row of a table or array of values and returns the value in the same column from a row you specify. * + * [Api set: ExcelApi 1.2] + * * @param lookupValue Is the value to be found in the first row of the table and can be a value, a reference, or a text string. * @param tableArray Is a table of text, numbers, or logical values in which data is looked up. tableArray can be a reference to a range or a range name. * @param rowIndexNum Is the row number in tableArray from which the matching value should be returned. The first row of values in the table is row 1. * @param rangeLookup Is a logical value: to find the closest match in the top row (sorted in ascending order) = TRUE or omitted; find an exact match = FALSE. - * - * [Api set: ExcelApi 1.2] */ hlookup(lookupValue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, tableArray: Excel.Range | number | Excel.RangeReference | Excel.FunctionResult, rowIndexNum: Excel.Range | number | Excel.RangeReference | Excel.FunctionResult, rangeLookup?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the harmonic mean of a data set of positive numbers: the reciprocal of the arithmetic mean of reciprocals. * - * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the harmonic mean. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the harmonic mean. */ harMean(...values: Array>): FunctionResult; /** * * Converts a Hexadecimal number to binary. * + * [Api set: ExcelApi 1.2] + * * @param number Is the hexadecimal number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ hex2Bin(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a hexadecimal number to decimal. * - * @param number Is the hexadecimal number you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the hexadecimal number you want to convert. */ hex2Dec(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a hexadecimal number to octal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the hexadecimal number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ hex2Oct(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hour as a number from 0 (12:00 A.M.) to 23 (11:00 P.M.). * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel, or text in time format, such as 16:48:00 or 4:48:00 PM. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel, or text in time format, such as 16:48:00 or 4:48:00 PM. */ hour(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hypergeometric distribution. * + * [Api set: ExcelApi 1.2] + * * @param sampleS Is the number of successes in the sample. * @param numberSample Is the size of the sample. * @param populationS Is the number of successes in the population. * @param numberPop Is the population size. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ hypGeom_Dist(sampleS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberSample: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, populationS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberPop: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Creates a shortcut or jump that opens a document stored on your hard drive, a network server, or on the Internet. * + * [Api set: ExcelApi 1.2] + * * @param linkLocation Is the text giving the path and file name to the document to be opened, a hard drive location, UNC address, or URL path. * @param friendlyName Is text or a number that is displayed in the cell. If omitted, the cell displays the linkLocation text. - * - * [Api set: ExcelApi 1.2] */ hyperlink(linkLocation: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, friendlyName?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number up, to the nearest integer or to the nearest multiple of significance. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value you want to round. * @param significance Is the optional multiple to which you want to round. - * - * [Api set: ExcelApi 1.2] */ iso_Ceiling(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a condition is met, and returns one value if TRUE, and another value if FALSE. * + * [Api set: ExcelApi 1.2] + * * @param logicalTest Is any value or expression that can be evaluated to TRUE or FALSE. * @param valueIfTrue Is the value that is returned if logicalTest is TRUE. If omitted, TRUE is returned. You can nest up to seven IF functions. * @param valueIfFalse Is the value that is returned if logicalTest is FALSE. If omitted, FALSE is returned. - * - * [Api set: ExcelApi 1.2] */ if(logicalTest: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, valueIfTrue?: Excel.Range | number | string | boolean | Excel.RangeReference | Excel.FunctionResult, valueIfFalse?: Excel.Range | number | string | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the absolute value (modulus) of a complex number. * - * @param inumber Is a complex number for which you want the absolute value. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the absolute value. */ imAbs(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the argument q, an angle expressed in radians. * - * @param inumber Is a complex number for which you want the argument. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the argument. */ imArgument(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the complex conjugate of a complex number. * - * @param inumber Is a complex number for which you want the conjugate. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the conjugate. */ imConjugate(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cosine of a complex number. * - * @param inumber Is a complex number for which you want the cosine. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the cosine. */ imCos(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic cosine of a complex number. * - * @param inumber Is a complex number for which you want the hyperbolic cosine. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the hyperbolic cosine. */ imCosh(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cotangent of a complex number. * - * @param inumber Is a complex number for which you want the cotangent. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the cotangent. */ imCot(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the cosecant of a complex number. * - * @param inumber Is a complex number for which you want the cosecant. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the cosecant. */ imCsc(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic cosecant of a complex number. * - * @param inumber Is a complex number for which you want the hyperbolic cosecant. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the hyperbolic cosecant. */ imCsch(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the quotient of two complex numbers. * + * [Api set: ExcelApi 1.2] + * * @param inumber1 Is the complex numerator or dividend. * @param inumber2 Is the complex denominator or divisor. - * - * [Api set: ExcelApi 1.2] */ imDiv(inumber1: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, inumber2: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the exponential of a complex number. * - * @param inumber Is a complex number for which you want the exponential. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the exponential. */ imExp(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the natural logarithm of a complex number. * - * @param inumber Is a complex number for which you want the natural logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the natural logarithm. */ imLn(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the base-10 logarithm of a complex number. * - * @param inumber Is a complex number for which you want the common logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the common logarithm. */ imLog10(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the base-2 logarithm of a complex number. * - * @param inumber Is a complex number for which you want the base-2 logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the base-2 logarithm. */ imLog2(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a complex number raised to an integer power. * + * [Api set: ExcelApi 1.2] + * * @param inumber Is a complex number you want to raise to a power. * @param number Is the power to which you want to raise the complex number. - * - * [Api set: ExcelApi 1.2] */ imPower(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the product of 1 to 255 complex numbers. * - * @param values Inumber1, Inumber2,... are from 1 to 255 complex numbers to multiply. - * * [Api set: ExcelApi 1.2] + * + * @param values Inumber1, Inumber2,... are from 1 to 255 complex numbers to multiply. */ imProduct(...values: Array>): FunctionResult; /** * * Returns the real coefficient of a complex number. * - * @param inumber Is a complex number for which you want the real coefficient. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the real coefficient. */ imReal(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the secant of a complex number. * - * @param inumber Is a complex number for which you want the secant. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the secant. */ imSec(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic secant of a complex number. * - * @param inumber Is a complex number for which you want the hyperbolic secant. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the hyperbolic secant. */ imSech(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sine of a complex number. * - * @param inumber Is a complex number for which you want the sine. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the sine. */ imSin(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic sine of a complex number. * - * @param inumber Is a complex number for which you want the hyperbolic sine. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the hyperbolic sine. */ imSinh(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the square root of a complex number. * - * @param inumber Is a complex number for which you want the square root. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the square root. */ imSqrt(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the difference of two complex numbers. * + * [Api set: ExcelApi 1.2] + * * @param inumber1 Is the complex number from which to subtract inumber2. * @param inumber2 Is the complex number to subtract from inumber1. - * - * [Api set: ExcelApi 1.2] */ imSub(inumber1: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, inumber2: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sum of complex numbers. * - * @param values List of parameters, whose elements are from 1 to 255 complex numbers to add. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are from 1 to 255 complex numbers to add. */ imSum(...values: Array>): FunctionResult; /** * * Returns the tangent of a complex number. * - * @param inumber Is a complex number for which you want the tangent. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the tangent. */ imTan(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the imaginary coefficient of a complex number. * - * @param inumber Is a complex number for which you want the imaginary coefficient. - * * [Api set: ExcelApi 1.2] + * + * @param inumber Is a complex number for which you want the imaginary coefficient. */ imaginary(inumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number down to the nearest integer. * - * @param number Is the real number you want to round down to an integer. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the real number you want to round down to an integer. */ int(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the interest rate for a fully invested security. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param investment Is the amount invested in the security. * @param redemption Is the amount to be received at maturity. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ intRate(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, investment: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the interest payment for a given period for an investment, based on periodic, constant payments and a constant interest rate. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param per Is the period for which you want to find the interest and must be in the range 1 to Nper. * @param nper Is the total number of payment periods in an investment. * @param pv Is the present value, or the lump-sum amount that a series of future payments is worth now. * @param fv Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, Fv = 0. * @param type Is a logical value representing the timing of payment: at the end of the period = 0 or omitted, at the beginning of the period = 1. - * - * [Api set: ExcelApi 1.2] */ ipmt(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, per: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the internal rate of return for a series of cash flows. * + * [Api set: ExcelApi 1.2] + * * @param values Is an array or a reference to cells that contain numbers for which you want to calculate the internal rate of return. * @param guess Is a number that you guess is close to the result of IRR; 0.1 (10 percent) if omitted. - * - * [Api set: ExcelApi 1.2] */ irr(values: Excel.Range | Excel.RangeReference | Excel.FunctionResult, guess?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is an error (#VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!) excluding #N/A, and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isErr(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is an error (#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!), and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isError(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns TRUE if the number is even. * - * @param number Is the value to test. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the value to test. */ isEven(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a reference is to a cell containing a formula, and returns TRUE or FALSE. * - * @param reference Is a reference to the cell you want to test. Reference can be a cell reference, a formula, or name that refers to a cell. - * * [Api set: ExcelApi 1.2] + * + * @param reference Is a reference to the cell you want to test. Reference can be a cell reference, a formula, or name that refers to a cell. */ isFormula(reference: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is a logical value (TRUE or FALSE), and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isLogical(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is #N/A, and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isNA(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is not text (blank cells are not text), and returns TRUE or FALSE. * - * @param value Is the value you want tested: a cell; a formula; or a name referring to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want tested: a cell; a formula; or a name referring to a cell, formula, or value. */ isNonText(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is a number, and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isNumber(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns TRUE if the number is odd. * - * @param number Is the value to test. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the value to test. */ isOdd(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is text, and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isText(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the ISO week number in the year for a given date. * - * @param date Is the date-time code used by Microsoft Excel for date and time calculation. - * * [Api set: ExcelApi 1.2] + * + * @param date Is the date-time code used by Microsoft Excel for date and time calculation. */ isoWeekNum(date: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the interest paid during a specific period of an investment. * + * [Api set: ExcelApi 1.2] + * * @param rate Interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param per Period for which you want to find the interest. * @param nper Number of payment periods in an investment. * @param pv Lump sum amount that a series of future payments is right now. - * - * [Api set: ExcelApi 1.2] */ ispmt(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, per: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is a reference, and returns TRUE or FALSE. * - * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want to test. Value can refer to a cell, a formula, or a name that refers to a cell, formula, or value. */ isref(value: Excel.Range | number | string | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the kurtosis of a data set. * - * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the kurtosis. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the kurtosis. */ kurt(...values: Array>): FunctionResult; /** * * Returns the k-th largest value in a data set. For example, the fifth largest number. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data for which you want to determine the k-th largest value. * @param k Is the position (from the largest) in the array or cell range of the value to return. - * - * [Api set: ExcelApi 1.2] */ large(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, k: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the least common multiple. * - * @param values List of parameters, whose elements are 1 to 255 values for which you want the least common multiple. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 values for which you want the least common multiple. */ lcm(...values: Array>): FunctionResult; /** * * Returns the specified number of characters from the start of a text string. * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string containing the characters you want to extract. * @param numChars Specifies how many characters you want LEFT to extract; 1 if omitted. - * - * [Api set: ExcelApi 1.2] */ left(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numChars?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the specified number of characters from the start of a text string. Use with double-byte character sets (DBCS). * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string containing the characters you want to extract. * @param numBytes Specifies how many characters you want LEFT to return. - * - * [Api set: ExcelApi 1.2] */ leftb(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numBytes?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of characters in a text string. * - * @param text Is the text whose length you want to find. Spaces count as characters. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text whose length you want to find. Spaces count as characters. */ len(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of characters in a text string. Use with double-byte character sets (DBCS). * - * @param text Is the text whose length you want to find. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text whose length you want to find. */ lenb(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the natural logarithm of a number. * - * @param number Is the positive real number for which you want the natural logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the positive real number for which you want the natural logarithm. */ ln(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the logarithm of a number to the base you specify. * + * [Api set: ExcelApi 1.2] + * * @param number Is the positive real number for which you want the logarithm. * @param base Is the base of the logarithm; 10 if omitted. - * - * [Api set: ExcelApi 1.2] */ log(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, base?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the base-10 logarithm of a number. * - * @param number Is the positive real number for which you want the base-10 logarithm. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the positive real number for which you want the base-10 logarithm. */ log10(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the lognormal distribution of x, where ln(x) is normally distributed with parameters Mean and Standard_dev. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function, a positive number. * @param mean Is the mean of ln(x). * @param standardDev Is the standard deviation of ln(x), a positive number. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ logNorm_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the lognormal cumulative distribution function of x, where ln(x) is normally distributed with parameters Mean and Standard_dev. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability associated with the lognormal distribution, a number between 0 and 1, inclusive. * @param mean Is the mean of ln(x). * @param standardDev Is the standard deviation of ln(x), a positive number. - * - * [Api set: ExcelApi 1.2] */ logNorm_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Looks up a value either from a one-row or one-column range or from an array. Provided for backward compatibility. * + * [Api set: ExcelApi 1.2] + * * @param lookupValue Is a value that LOOKUP searches for in lookupVector and can be a number, text, a logical value, or a name or reference to a value. * @param lookupVector Is a range that contains only one row or one column of text, numbers, or logical values, placed in ascending order. * @param resultVector Is a range that contains only one row or column, the same size as lookupVector. - * - * [Api set: ExcelApi 1.2] */ lookup(lookupValue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, lookupVector: Excel.Range | Excel.RangeReference | Excel.FunctionResult, resultVector?: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts all letters in a text string to lowercase. * - * @param text Is the text you want to convert to lowercase. Characters in Text that are not letters are not changed. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text you want to convert to lowercase. Characters in Text that are not letters are not changed. */ lower(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Macauley modified duration for a security with an assumed par value of $100. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param coupon Is the security's annual coupon rate. * @param yld Is the security's annual yield. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ mduration(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, coupon: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the internal rate of return for a series of periodic cash flows, considering both cost of investment and interest on reinvestment of cash. * + * [Api set: ExcelApi 1.2] + * * @param values Is an array or a reference to cells that contain numbers that represent a series of payments (negative) and income (positive) at regular periods. * @param financeRate Is the interest rate you pay on the money used in the cash flows. * @param reinvestRate Is the interest rate you receive on the cash flows as you reinvest them. - * - * [Api set: ExcelApi 1.2] */ mirr(values: Excel.Range | Excel.RangeReference | Excel.FunctionResult, financeRate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, reinvestRate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a number rounded to the desired multiple. * + * [Api set: ExcelApi 1.2] + * * @param number Is the value to round. * @param multiple Is the multiple to which you want to round number. - * - * [Api set: ExcelApi 1.2] */ mround(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, multiple: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the relative position of an item in an array that matches a specified value in a specified order. * + * [Api set: ExcelApi 1.2] + * * @param lookupValue Is the value you use to find the value you want in the array, a number, text, or logical value, or a reference to one of these. * @param lookupArray Is a contiguous range of cells containing possible lookup values, an array of values, or a reference to an array. * @param matchType Is a number 1, 0, or -1 indicating which value to return. - * - * [Api set: ExcelApi 1.2] */ match(lookupValue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, lookupArray: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, matchType?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the largest value in a set of values. Ignores logical values and text. * - * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the maximum. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the maximum. */ max(...values: Array>): FunctionResult; /** * * Returns the largest value in a set of values. Does not ignore logical values and text. * - * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the maximum. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the maximum. */ maxA(...values: Array>): FunctionResult; /** * * Returns the median, or the number in the middle of the set of given numbers. * - * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the median. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the median. */ median(...values: Array>): FunctionResult; /** * * Returns the characters from the middle of a text string, given a starting position and length. * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string from which you want to extract the characters. * @param startNum Is the position of the first character you want to extract. The first character in Text is 1. * @param numChars Specifies how many characters to return from Text. - * - * [Api set: ExcelApi 1.2] */ mid(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numChars: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns characters from the middle of a text string, given a starting position and length. Use with double-byte character sets (DBCS). * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string containing the characters you want to extract. * @param startNum Is the position of the first character you want to extract in text. * @param numBytes Specifies how many characters to return from text. - * - * [Api set: ExcelApi 1.2] */ midb(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numBytes: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the smallest number in a set of values. Ignores logical values and text. * - * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the minimum. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the minimum. */ min(...values: Array>): FunctionResult; /** * * Returns the smallest value in a set of values. Does not ignore logical values and text. * - * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the minimum. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, empty cells, logical values, or text numbers for which you want the minimum. */ minA(...values: Array>): FunctionResult; /** * * Returns the minute, a number from 0 to 59. * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:00 or 4:48:00 PM. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:00 or 4:48:00 PM. */ minute(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the remainder after a number is divided by a divisor. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number for which you want to find the remainder after the division is performed. * @param divisor Is the number by which you want to divide Number. - * - * [Api set: ExcelApi 1.2] */ mod(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, divisor: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the month, a number from 1 (January) to 12 (December). * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel. */ month(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the multinomial of a set of numbers. * - * @param values List of parameters, whose elements are 1 to 255 values for which you want the multinomial. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 values for which you want the multinomial. */ multiNomial(...values: Array>): FunctionResult; /** * * Converts non-number value to a number, dates to serial numbers, TRUE to 1, anything else to 0 (zero). * - * @param value Is the value you want converted. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value you want converted. */ n(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of periods for an investment based on periodic, constant payments and a constant interest rate. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param pmt Is the payment made each period; it cannot change over the life of the investment. * @param pv Is the present value, or the lump-sum amount that a series of future payments is worth now. * @param fv Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, zero is used. * @param type Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. - * - * [Api set: ExcelApi 1.2] */ nper(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pmt: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -8954,96 +11404,96 @@ declare module Excel { * * Returns the negative binomial distribution, the probability that there will be Number_f failures before the Number_s-th success, with Probability_s probability of a success. * + * [Api set: ExcelApi 1.2] + * * @param numberF Is the number of failures. * @param numberS Is the threshold number of successes. * @param probabilityS Is the probability of a success; a number between 0 and 1. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ negBinom_Dist(numberF: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, probabilityS: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of whole workdays between two dates. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param endDate Is a serial date number that represents the end date. * @param holidays Is an optional set of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays. - * - * [Api set: ExcelApi 1.2] */ networkDays(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, holidays?: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of whole workdays between two dates with custom weekend parameters. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param endDate Is a serial date number that represents the end date. * @param weekend Is a number or string specifying when weekends occur. * @param holidays Is an optional set of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays. - * - * [Api set: ExcelApi 1.2] */ networkDays_Intl(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, weekend?: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, holidays?: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the annual nominal interest rate. * + * [Api set: ExcelApi 1.2] + * * @param effectRate Is the effective interest rate. * @param npery Is the number of compounding periods per year. - * - * [Api set: ExcelApi 1.2] */ nominal(effectRate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, npery: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the normal distribution for the specified mean and standard deviation. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value for which you want the distribution. * @param mean Is the arithmetic mean of the distribution. * @param standardDev Is the standard deviation of the distribution, a positive number. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ norm_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * + * [Api set: ExcelApi 1.2] + * * @param probability Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive. * @param mean Is the arithmetic mean of the distribution. * @param standardDev Is the standard deviation of the distribution, a positive number. - * - * [Api set: ExcelApi 1.2] */ norm_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the standard normal distribution (has a mean of zero and a standard deviation of one). * + * [Api set: ExcelApi 1.2] + * * @param z Is the value for which you want the distribution. * @param cumulative Is a logical value for the function to return: the cumulative distribution function = TRUE; the probability density function = FALSE. - * - * [Api set: ExcelApi 1.2] */ norm_S_Dist(z: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the inverse of the standard normal cumulative distribution (has a mean of zero and a standard deviation of one). * - * @param probability Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive. - * * [Api set: ExcelApi 1.2] + * + * @param probability Is a probability corresponding to the normal distribution, a number between 0 and 1 inclusive. */ norm_S_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Changes FALSE to TRUE, or TRUE to FALSE. * - * @param logical Is a value or expression that can be evaluated to TRUE or FALSE. - * * [Api set: ExcelApi 1.2] + * + * @param logical Is a value or expression that can be evaluated to TRUE or FALSE. */ not(logical: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -9057,65 +11507,67 @@ declare module Excel { * * Returns the net present value of an investment based on a discount rate and a series of future payments (negative values) and income (positive values). * + * [Api set: ExcelApi 1.2] + * * @param rate Is the rate of discount over the length of one period. * @param values List of parameters, whose elements are 1 to 254 payments and income, equally spaced in time and occurring at the end of each period. - * - * [Api set: ExcelApi 1.2] */ npv(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, ...values: Array>): FunctionResult; /** * * Converts text to number in a locale-independent manner. * + * [Api set: ExcelApi 1.2] + * * @param text Is the string representing the number you want to convert. * @param decimalSeparator Is the character used as the decimal separator in the string. * @param groupSeparator Is the character used as the group separator in the string. - * - * [Api set: ExcelApi 1.2] */ numberValue(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, decimalSeparator?: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, groupSeparator?: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts an octal number to binary. * + * [Api set: ExcelApi 1.2] + * * @param number Is the octal number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ oct2Bin(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts an octal number to decimal. * - * @param number Is the octal number you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the octal number you want to convert. */ oct2Dec(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts an octal number to hexadecimal. * + * [Api set: ExcelApi 1.2] + * * @param number Is the octal number you want to convert. * @param places Is the number of characters to use. - * - * [Api set: ExcelApi 1.2] */ oct2Hex(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, places?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a positive number up and negative number down to the nearest odd integer. * - * @param number Is the value to round. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the value to round. */ odd(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value of a security with an odd first period. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param issue Is the security's issue date, expressed as a serial date number. @@ -9125,14 +11577,14 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ oddFPrice(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, firstCoupon: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the yield of a security with an odd first period. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param issue Is the security's issue date, expressed as a serial date number. @@ -9142,14 +11594,14 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ oddFYield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, firstCoupon: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value of a security with an odd last period. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param lastInterest Is the security's last coupon date, expressed as a serial date number. @@ -9158,14 +11610,14 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ oddLPrice(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, lastInterest: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the yield of a security with an odd last period. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param lastInterest Is the security's last coupon date, expressed as a serial date number. @@ -9174,99 +11626,97 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ oddLYield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, lastInterest: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether any of the arguments are TRUE, and returns TRUE or FALSE. Returns FALSE only if all arguments are FALSE. * - * @param values List of parameters, whose elements are 1 to 255 conditions that you want to test that can be either TRUE or FALSE. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 conditions that you want to test that can be either TRUE or FALSE. */ or(...values: Array>): FunctionResult; /** * * Returns the number of periods required by an investment to reach a specified value. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. * @param pv Is the present value of the investment. * @param fv Is the desired future value of the investment. - * - * [Api set: ExcelApi 1.2] */ pduration(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the rank of a value in a data set as a percentage of the data set as a percentage (0..1, exclusive) of the data set. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data with numeric values that defines relative standing. * @param x Is the value for which you want to know the rank. * @param significance Is an optional value that identifies the number of significant digits for the returned percentage, three digits if omitted (0.xxx%). - * - * [Api set: ExcelApi 1.2] */ percentRank_Exc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the rank of a value in a data set as a percentage of the data set as a percentage (0..1, inclusive) of the data set. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data with numeric values that defines relative standing. * @param x Is the value for which you want to know the rank. * @param significance Is an optional value that identifies the number of significant digits for the returned percentage, three digits if omitted (0.xxx%). - * - * [Api set: ExcelApi 1.2] */ percentRank_Inc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, significance?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the k-th percentile of values in a range, where k is in the range 0..1, exclusive. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data that defines relative standing. * @param k Is the percentile value that is between 0 through 1, inclusive. - * - * [Api set: ExcelApi 1.2] */ percentile_Exc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, k: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the k-th percentile of values in a range, where k is in the range 0..1, inclusive. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data that defines relative standing. * @param k Is the percentile value that is between 0 through 1, inclusive. - * - * [Api set: ExcelApi 1.2] */ percentile_Inc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, k: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of permutations for a given number of objects that can be selected from the total objects. * + * [Api set: ExcelApi 1.2] + * * @param number Is the total number of objects. * @param numberChosen Is the number of objects in each permutation. - * - * [Api set: ExcelApi 1.2] */ permut(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberChosen: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of permutations for a given number of objects (with repetitions) that can be selected from the total objects. * + * [Api set: ExcelApi 1.2] + * * @param number Is the total number of objects. * @param numberChosen Is the number of objects in each permutation. - * - * [Api set: ExcelApi 1.2] */ permutationa(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberChosen: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the value of the density function for a standard normal distribution. * - * @param x Is the number for which you want the density of the standard normal distribution. - * * [Api set: ExcelApi 1.2] + * + * @param x Is the number for which you want the density of the standard normal distribution. */ phi(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -9280,54 +11730,56 @@ declare module Excel { * * Calculates the payment for a loan based on constant payments and a constant interest rate. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period for the loan. For example, use 6%/4 for quarterly payments at 6% APR. * @param nper Is the total number of payments for the loan. * @param pv Is the present value: the total amount that a series of future payments is worth now. * @param fv Is the future value, or a cash balance you want to attain after the last payment is made, 0 (zero) if omitted. * @param type Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. - * - * [Api set: ExcelApi 1.2] */ pmt(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Poisson distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the number of events. * @param mean Is the expected numeric value, a positive number. * @param cumulative Is a logical value: for the cumulative Poisson probability, use TRUE; for the Poisson probability mass function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ poisson_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the result of a number raised to a power. * + * [Api set: ExcelApi 1.2] + * * @param number Is the base number, any real number. * @param power Is the exponent, to which the base number is raised. - * - * [Api set: ExcelApi 1.2] */ power(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, power: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the payment on the principal for a given investment based on periodic, constant payments and a constant interest rate. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param per Specifies the period and must be in the range 1 to nper. * @param nper Is the total number of payment periods in an investment. * @param pv Is the present value: the total amount that a series of future payments is worth now. * @param fv Is the future value, or cash balance you want to attain after the last payment is made. * @param type Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. - * - * [Api set: ExcelApi 1.2] */ ppmt(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, per: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value of a security that pays periodic interest. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param rate Is the security's annual coupon rate. @@ -9335,105 +11787,103 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ price(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value of a discounted security. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param discount Is the security's discount rate. * @param redemption Is the security's redemption value per $100 face value. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ priceDisc(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, discount: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value of a security that pays interest at maturity. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param issue Is the security's issue date, expressed as a serial date number. * @param rate Is the security's interest rate at date of issue. * @param yld Is the security's annual yield. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ priceMat(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, yld: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Multiplies all the numbers given as arguments. * - * @param values List of parameters, whose elements are 1 to 255 numbers, logical values, or text representations of numbers that you want to multiply. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, logical values, or text representations of numbers that you want to multiply. */ product(...values: Array>): FunctionResult; /** * * Converts a text string to proper case; the first letter in each word to uppercase, and all other letters to lowercase. * - * @param text Is text enclosed in quotation marks, a formula that returns text, or a reference to a cell containing text to partially capitalize. - * * [Api set: ExcelApi 1.2] + * + * @param text Is text enclosed in quotation marks, a formula that returns text, or a reference to a cell containing text to partially capitalize. */ proper(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the present value of an investment: the total amount that a series of future payments is worth now. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the interest rate per period. For example, use 6%/4 for quarterly payments at 6% APR. * @param nper Is the total number of payment periods in an investment. * @param pmt Is the payment made each period and cannot change over the life of the investment. * @param fv Is the future value, or a cash balance you want to attain after the last payment is made. * @param type Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. - * - * [Api set: ExcelApi 1.2] */ pv(rate: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pmt: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the quartile of a data set, based on percentile values from 0..1, exclusive. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or cell range of numeric values for which you want the quartile value. * @param quart Is a number: minimum value = 0; 1st quartile = 1; median value = 2; 3rd quartile = 3; maximum value = 4. - * - * [Api set: ExcelApi 1.2] */ quartile_Exc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, quart: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the quartile of a data set, based on percentile values from 0..1, inclusive. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or cell range of numeric values for which you want the quartile value. * @param quart Is a number: minimum value = 0; 1st quartile = 1; median value = 2; 3rd quartile = 3; maximum value = 4. - * - * [Api set: ExcelApi 1.2] */ quartile_Inc(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, quart: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the integer portion of a division. * + * [Api set: ExcelApi 1.2] + * * @param numerator Is the dividend. * @param denominator Is the divisor. - * - * [Api set: ExcelApi 1.2] */ quotient(numerator: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, denominator: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts degrees to radians. * - * @param angle Is an angle in degrees that you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param angle Is an angle in degrees that you want to convert. */ radians(angle: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -9447,575 +11897,575 @@ declare module Excel { * * Returns a random number between the numbers you specify. * + * [Api set: ExcelApi 1.2] + * * @param bottom Is the smallest integer RANDBETWEEN will return. * @param top Is the largest integer RANDBETWEEN will return. - * - * [Api set: ExcelApi 1.2] */ randBetween(bottom: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, top: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the rank of a number in a list of numbers: its size relative to other values in the list; if more than one value has the same rank, the average rank is returned. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number for which you want to find the rank. * @param ref Is an array of, or a reference to, a list of numbers. Nonnumeric values are ignored. * @param order Is a number: rank in the list sorted descending = 0 or omitted; rank in the list sorted ascending = any nonzero value. - * - * [Api set: ExcelApi 1.2] */ rank_Avg(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, ref: Excel.Range | Excel.RangeReference | Excel.FunctionResult, order?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the rank of a number in a list of numbers: its size relative to other values in the list; if more than one value has the same rank, the top rank of that set of values is returned. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number for which you want to find the rank. * @param ref Is an array of, or a reference to, a list of numbers. Nonnumeric values are ignored. * @param order Is a number: rank in the list sorted descending = 0 or omitted; rank in the list sorted ascending = any nonzero value. - * - * [Api set: ExcelApi 1.2] */ rank_Eq(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, ref: Excel.Range | Excel.RangeReference | Excel.FunctionResult, order?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the interest rate per period of a loan or an investment. For example, use 6%/4 for quarterly payments at 6% APR. * + * [Api set: ExcelApi 1.2] + * * @param nper Is the total number of payment periods for the loan or investment. * @param pmt Is the payment made each period and cannot change over the life of the loan or investment. * @param pv Is the present value: the total amount that a series of future payments is worth now. * @param fv Is the future value, or a cash balance you want to attain after the last payment is made. If omitted, uses Fv = 0. * @param type Is a logical value: payment at the beginning of the period = 1; payment at the end of the period = 0 or omitted. * @param guess Is your guess for what the rate will be; if omitted, Guess = 0.1 (10 percent). - * - * [Api set: ExcelApi 1.2] */ rate(nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pmt: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, type?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, guess?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the amount received at maturity for a fully invested security. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param investment Is the amount invested in the security. * @param discount Is the security's discount rate. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ received(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, investment: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, discount: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Replaces part of a text string with a different text string. * + * [Api set: ExcelApi 1.2] + * * @param oldText Is text in which you want to replace some characters. * @param startNum Is the position of the character in oldText that you want to replace with newText. * @param numChars Is the number of characters in oldText that you want to replace. * @param newText Is the text that will replace characters in oldText. - * - * [Api set: ExcelApi 1.2] */ replace(oldText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numChars: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, newText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Replaces part of a text string with a different text string. Use with double-byte character sets (DBCS). * + * [Api set: ExcelApi 1.2] + * * @param oldText Is text in which you want to replace some characters. * @param startNum Is the position of the character in oldText that you want to replace with newText. * @param numBytes Is the number of characters in oldText that you want to replace with newText. * @param newText Is the text that will replace characters in oldText. - * - * [Api set: ExcelApi 1.2] */ replaceB(oldText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numBytes: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, newText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Repeats text a given number of times. Use REPT to fill a cell with a number of instances of a text string. * + * [Api set: ExcelApi 1.2] + * * @param text Is the text you want to repeat. * @param numberTimes Is a positive number specifying the number of times to repeat text. - * - * [Api set: ExcelApi 1.2] */ rept(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numberTimes: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the specified number of characters from the end of a text string. * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string that contains the characters you want to extract. * @param numChars Specifies how many characters you want to extract, 1 if omitted. - * - * [Api set: ExcelApi 1.2] */ right(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numChars?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the specified number of characters from the end of a text string. Use with double-byte character sets (DBCS). * + * [Api set: ExcelApi 1.2] + * * @param text Is the text string containing the characters you want to extract. * @param numBytes Specifies how many characters you want to extract. - * - * [Api set: ExcelApi 1.2] */ rightb(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numBytes?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts an Arabic numeral to Roman, as text. * + * [Api set: ExcelApi 1.2] + * * @param number Is the Arabic numeral you want to convert. * @param form Is the number specifying the type of Roman numeral you want. - * - * [Api set: ExcelApi 1.2] */ roman(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, form?: boolean | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number to a specified number of digits. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number you want to round. * @param numDigits Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero to the nearest integer. - * - * [Api set: ExcelApi 1.2] */ round(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numDigits: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number down, toward zero. * + * [Api set: ExcelApi 1.2] + * * @param number Is any real number that you want rounded down. * @param numDigits Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero or omitted, to the nearest integer. - * - * [Api set: ExcelApi 1.2] */ roundDown(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numDigits: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Rounds a number up, away from zero. * + * [Api set: ExcelApi 1.2] + * * @param number Is any real number that you want rounded up. * @param numDigits Is the number of digits to which you want to round. Negative rounds to the left of the decimal point; zero or omitted, to the nearest integer. - * - * [Api set: ExcelApi 1.2] */ roundUp(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numDigits: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of rows in a reference or array. * - * @param array Is an array, an array formula, or a reference to a range of cells for which you want the number of rows. - * * [Api set: ExcelApi 1.2] + * + * @param array Is an array, an array formula, or a reference to a range of cells for which you want the number of rows. */ rows(array: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns an equivalent interest rate for the growth of an investment. * + * [Api set: ExcelApi 1.2] + * * @param nper Is the number of periods for the investment. * @param pv Is the present value of the investment. * @param fv Is the future value of the investment. - * - * [Api set: ExcelApi 1.2] */ rri(nper: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, fv: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the secant of an angle. * - * @param number Is the angle in radians for which you want the secant. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the secant. */ sec(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic secant of an angle. * - * @param number Is the angle in radians for which you want the hyperbolic secant. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the hyperbolic secant. */ sech(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the second, a number from 0 to 59. * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:23 or 4:48:47 PM. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel or text in time format, such as 16:48:23 or 4:48:47 PM. */ second(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sum of a power series based on the formula. * + * [Api set: ExcelApi 1.2] + * * @param x Is the input value to the power series. * @param n Is the initial power to which you want to raise x. * @param m Is the step by which to increase n for each term in the series. * @param coefficients Is a set of coefficients by which each successive power of x is multiplied. - * - * [Api set: ExcelApi 1.2] */ seriesSum(x: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, n: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, m: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, coefficients: Excel.Range | string | number | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sheet number of the referenced sheet. * - * @param value Is the name of a sheet or a reference that you want the sheet number of. If omitted the number of the sheet containing the function is returned. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the name of a sheet or a reference that you want the sheet number of. If omitted the number of the sheet containing the function is returned. */ sheet(value?: Excel.Range | string | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number of sheets in a reference. * - * @param reference Is a reference for which you want to know the number of sheets it contains. If omitted the number of sheets in the workbook containing the function is returned. - * * [Api set: ExcelApi 1.2] + * + * @param reference Is a reference for which you want to know the number of sheets it contains. If omitted the number of sheets in the workbook containing the function is returned. */ sheets(reference?: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sign of a number: 1 if the number is positive, zero if the number is zero, or -1 if the number is negative. * - * @param number Is any real number. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number. */ sign(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the sine of an angle. * - * @param number Is the angle in radians for which you want the sine. Degrees * PI()/180 = radians. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the sine. Degrees * PI()/180 = radians. */ sin(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic sine of a number. * - * @param number Is any real number. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number. */ sinh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the skewness of a distribution: a characterization of the degree of asymmetry of a distribution around its mean. * - * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the skewness. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers or names, arrays, or references that contain numbers for which you want the skewness. */ skew(...values: Array>): FunctionResult; /** * * Returns the skewness of a distribution based on a population: a characterization of the degree of asymmetry of a distribution around its mean. * - * @param values List of parameters, whose elements are 1 to 254 numbers or names, arrays, or references that contain numbers for which you want the population skewness. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 254 numbers or names, arrays, or references that contain numbers for which you want the population skewness. */ skew_p(...values: Array>): FunctionResult; /** * * Returns the straight-line depreciation of an asset for one period. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the initial cost of the asset. * @param salvage Is the salvage value at the end of the life of the asset. * @param life Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset). - * - * [Api set: ExcelApi 1.2] */ sln(cost: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, life: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the k-th smallest value in a data set. For example, the fifth smallest number. * + * [Api set: ExcelApi 1.2] + * * @param array Is an array or range of numerical data for which you want to determine the k-th smallest value. * @param k Is the position (from the smallest) in the array or range of the value to return. - * - * [Api set: ExcelApi 1.2] */ small(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, k: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the square root of a number. * - * @param number Is the number for which you want the square root. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the number for which you want the square root. */ sqrt(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the square root of (number * Pi). * - * @param number Is the number by which p is multiplied. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the number by which p is multiplied. */ sqrtPi(number: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Estimates standard deviation based on a sample, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1. * - * @param values List of parameters, whose elements are 1 to 255 values corresponding to a sample of a population and can be values or names or references to values. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 values corresponding to a sample of a population and can be values or names or references to values. */ stDevA(...values: Array>): FunctionResult; /** * * Calculates standard deviation based on an entire population, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1. * - * @param values List of parameters, whose elements are 1 to 255 values corresponding to a population and can be values, names, arrays, or references that contain values. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 values corresponding to a population and can be values, names, arrays, or references that contain values. */ stDevPA(...values: Array>): FunctionResult; /** * * Calculates standard deviation based on the entire population given as arguments (ignores logical values and text). * - * @param values List of parameters, whose elements are 1 to 255 numbers corresponding to a population and can be numbers or references that contain numbers. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers corresponding to a population and can be numbers or references that contain numbers. */ stDev_P(...values: Array>): FunctionResult; /** * * Estimates standard deviation based on a sample (ignores logical values and text in the sample). * - * @param values List of parameters, whose elements are 1 to 255 numbers corresponding to a sample of a population and can be numbers or references that contain numbers. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers corresponding to a sample of a population and can be numbers or references that contain numbers. */ stDev_S(...values: Array>): FunctionResult; /** * * Returns a normalized value from a distribution characterized by a mean and standard deviation. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value you want to normalize. * @param mean Is the arithmetic mean of the distribution. * @param standardDev Is the standard deviation of the distribution, a positive number. - * - * [Api set: ExcelApi 1.2] */ standardize(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, mean: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, standardDev: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Replaces existing text with new text in a text string. * + * [Api set: ExcelApi 1.2] + * * @param text Is the text or the reference to a cell containing text in which you want to substitute characters. * @param oldText Is the existing text you want to replace. If the case of oldText does not match the case of text, SUBSTITUTE will not replace the text. * @param newText Is the text you want to replace oldText with. * @param instanceNum Specifies which occurrence of oldText you want to replace. If omitted, every instance of oldText is replaced. - * - * [Api set: ExcelApi 1.2] */ substitute(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, oldText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, newText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, instanceNum?: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a subtotal in a list or database. * + * [Api set: ExcelApi 1.2] + * * @param functionNum Is the number 1 to 11 that specifies the summary function for the subtotal. * @param values List of parameters, whose elements are 1 to 254 ranges or references for which you want the subtotal. - * - * [Api set: ExcelApi 1.2] */ subtotal(functionNum: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, ...values: Array>): FunctionResult; /** * * Adds all the numbers in a range of cells. * - * @param values List of parameters, whose elements are 1 to 255 numbers to sum. Logical values and text are ignored in cells, included if typed as arguments. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers to sum. Logical values and text are ignored in cells, included if typed as arguments. */ sum(...values: Array>): FunctionResult; /** * * Adds the cells specified by a given condition or criteria. * + * [Api set: ExcelApi 1.2] + * * @param range Is the range of cells you want evaluated. * @param criteria Is the condition or criteria in the form of a number, expression, or text that defines which cells will be added. * @param sumRange Are the actual cells to sum. If omitted, the cells in range are used. - * - * [Api set: ExcelApi 1.2] */ sumIf(range: Excel.Range | Excel.RangeReference | Excel.FunctionResult, criteria: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, sumRange?: Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Adds the cells specified by a given set of conditions or criteria. * + * [Api set: ExcelApi 1.2] + * * @param sumRange Are the actual cells to sum. * @param values List of parameters, where the first element of each pair is the Is the range of cells you want evaluated for the particular condition , and the second element is is the condition or criteria in the form of a number, expression, or text that defines which cells will be added. - * - * [Api set: ExcelApi 1.2] */ sumIfs(sumRange: Excel.Range | Excel.RangeReference | Excel.FunctionResult, ...values: Array | number | string | boolean>): FunctionResult; /** * * Returns the sum of the squares of the arguments. The arguments can be numbers, arrays, names, or references to cells that contain numbers. * - * @param values List of parameters, whose elements are 1 to 255 numbers, arrays, names, or references to arrays for which you want the sum of the squares. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numbers, arrays, names, or references to arrays for which you want the sum of the squares. */ sumSq(...values: Array>): FunctionResult; /** * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the initial cost of the asset. * @param salvage Is the salvage value at the end of the life of the asset. * @param life Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset). * @param per Is the period and must use the same units as Life. - * - * [Api set: ExcelApi 1.2] */ syd(cost: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, life: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, per: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Checks whether a value is text, and returns the text if it is, or returns double quotes (empty text) if it is not. * - * @param value Is the value to test. - * * [Api set: ExcelApi 1.2] + * + * @param value Is the value to test. */ t(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the bond-equivalent yield for a treasury bill. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the Treasury bill's settlement date, expressed as a serial date number. * @param maturity Is the Treasury bill's maturity date, expressed as a serial date number. * @param discount Is the Treasury bill's discount rate. - * - * [Api set: ExcelApi 1.2] */ tbillEq(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, discount: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the price per $100 face value for a treasury bill. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the Treasury bill's settlement date, expressed as a serial date number. * @param maturity Is the Treasury bill's maturity date, expressed as a serial date number. * @param discount Is the Treasury bill's discount rate. - * - * [Api set: ExcelApi 1.2] */ tbillPrice(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, discount: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the yield for a treasury bill. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the Treasury bill's settlement date, expressed as a serial date number. * @param maturity Is the Treasury bill's maturity date, expressed as a serial date number. * @param pr Is the Treasury Bill's price per $100 face value. - * - * [Api set: ExcelApi 1.2] */ tbillYield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the left-tailed Student's t-distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the numeric value at which to evaluate the distribution. * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ t_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the two-tailed Student's t-distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the numeric value at which to evaluate the distribution. * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. - * - * [Api set: ExcelApi 1.2] */ t_Dist_2T(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the right-tailed Student's t-distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the numeric value at which to evaluate the distribution. * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. - * - * [Api set: ExcelApi 1.2] */ t_Dist_RT(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the left-tailed inverse of the Student's t-distribution. * + * [Api set: ExcelApi 1.2] + * * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. - * - * [Api set: ExcelApi 1.2] */ t_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the two-tailed inverse of the Student's t-distribution. * + * [Api set: ExcelApi 1.2] + * * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. - * - * [Api set: ExcelApi 1.2] */ t_Inv_2T(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the tangent of an angle. * - * @param number Is the angle in radians for which you want the tangent. Degrees * PI()/180 = radians. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the angle in radians for which you want the tangent. Degrees * PI()/180 = radians. */ tan(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the hyperbolic tangent of a number. * - * @param number Is any real number. - * * [Api set: ExcelApi 1.2] + * + * @param number Is any real number. */ tanh(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a value to text in a specific number format. * + * [Api set: ExcelApi 1.2] + * * @param value Is a number, a formula that evaluates to a numeric value, or a reference to a cell containing a numeric value. * @param formatText Is a number format in text form from the Category box on the Number tab in the Format Cells dialog box (not General). - * - * [Api set: ExcelApi 1.2] */ text(value: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, formatText: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts hours, minutes, and seconds given as numbers to an Excel serial number, formatted with a time format. * + * [Api set: ExcelApi 1.2] + * * @param hour Is a number from 0 to 23 representing the hour. * @param minute Is a number from 0 to 59 representing the minute. * @param second Is a number from 0 to 59 representing the second. - * - * [Api set: ExcelApi 1.2] */ time(hour: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, minute: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, second: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a text time to an Excel serial number for a time, a number from 0 (12:00:00 AM) to 0.999988426 (11:59:59 PM). Format the number with a time format after entering the formula. * - * @param timeText Is a text string that gives a time in any one of the Microsoft Excel time formats (date information in the string is ignored). - * * [Api set: ExcelApi 1.2] + * + * @param timeText Is a text string that gives a time in any one of the Microsoft Excel time formats (date information in the string is ignored). */ timevalue(timeText: string | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -10029,19 +12479,19 @@ declare module Excel { * * Removes all spaces from a text string except for single spaces between words. * - * @param text Is the text from which you want spaces removed. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text from which you want spaces removed. */ trim(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the mean of the interior portion of a set of data values. * + * [Api set: ExcelApi 1.2] + * * @param array Is the range or array of values to trim and average. * @param percent Is the fractional number of data points to exclude from the top and bottom of the data set. - * - * [Api set: ExcelApi 1.2] */ trimMean(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, percent: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** @@ -10055,119 +12505,121 @@ declare module Excel { * * Truncates a number to an integer by removing the decimal, or fractional, part of the number. * + * [Api set: ExcelApi 1.2] + * * @param number Is the number you want to truncate. * @param numDigits Is a number specifying the precision of the truncation, 0 (zero) if omitted. - * - * [Api set: ExcelApi 1.2] */ trunc(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, numDigits?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns an integer representing the data type of a value: number = 1; text = 2; logical value = 4; error value = 16; array = 64. * - * @param value Can be any value. - * * [Api set: ExcelApi 1.2] + * + * @param value Can be any value. */ type(value: boolean | string | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a number to text, using currency format. * + * [Api set: ExcelApi 1.2] + * * @param number Is a number, a reference to a cell containing a number, or a formula that evaluates to a number. * @param decimals Is the number of digits to the right of the decimal point. - * - * [Api set: ExcelApi 1.2] */ usdollar(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, decimals?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Unicode character referenced by the given numeric value. * - * @param number Is the Unicode number representing a character. - * * [Api set: ExcelApi 1.2] + * + * @param number Is the Unicode number representing a character. */ unichar(number: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the number (code point) corresponding to the first character of the text. * - * @param text Is the character that you want the Unicode value of. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the character that you want the Unicode value of. */ unicode(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a text string to all uppercase letters. * - * @param text Is the text you want converted to uppercase, a reference or a text string. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text you want converted to uppercase, a reference or a text string. */ upper(text: string | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Looks for a value in the leftmost column of a table, and then returns a value in the same row from a column you specify. By default, the table must be sorted in an ascending order. * + * [Api set: ExcelApi 1.2] + * * @param lookupValue Is the value to be found in the first column of the table, and can be a value, a reference, or a text string. * @param tableArray Is a table of text, numbers, or logical values, in which data is retrieved. tableArray can be a reference to a range or a range name. * @param colIndexNum Is the column number in tableArray from which the matching value should be returned. The first column of values in the table is column 1. * @param rangeLookup Is a logical value: to find the closest match in the first column (sorted in ascending order) = TRUE or omitted; find an exact match = FALSE. - * - * [Api set: ExcelApi 1.2] */ vlookup(lookupValue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, tableArray: Excel.Range | number | Excel.RangeReference | Excel.FunctionResult, colIndexNum: Excel.Range | number | Excel.RangeReference | Excel.FunctionResult, rangeLookup?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Converts a text string that represents a number to a number. * - * @param text Is the text enclosed in quotation marks or a reference to a cell containing the text you want to convert. - * * [Api set: ExcelApi 1.2] + * + * @param text Is the text enclosed in quotation marks or a reference to a cell containing the text you want to convert. */ value(text: string | boolean | number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Estimates variance based on a sample, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1. * - * @param values List of parameters, whose elements are 1 to 255 value arguments corresponding to a sample of a population. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 value arguments corresponding to a sample of a population. */ varA(...values: Array>): FunctionResult; /** * * Calculates variance based on the entire population, including logical values and text. Text and the logical value FALSE have the value 0; the logical value TRUE has the value 1. * - * @param values List of parameters, whose elements are 1 to 255 value arguments corresponding to a population. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 value arguments corresponding to a population. */ varPA(...values: Array>): FunctionResult; /** * * Calculates variance based on the entire population (ignores logical values and text in the population). * - * @param values List of parameters, whose elements are 1 to 255 numeric arguments corresponding to a population. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numeric arguments corresponding to a population. */ var_P(...values: Array>): FunctionResult; /** * * Estimates variance based on a sample (ignores logical values and text in the sample). * - * @param values List of parameters, whose elements are 1 to 255 numeric arguments corresponding to a sample of a population. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 255 numeric arguments corresponding to a sample of a population. */ var_S(...values: Array>): FunctionResult; /** * * Returns the depreciation of an asset for any period you specify, including partial periods, using the double-declining balance method or some other method you specify. * + * [Api set: ExcelApi 1.2] + * * @param cost Is the initial cost of the asset. * @param salvage Is the salvage value at the end of the life of the asset. * @param life Is the number of periods over which the asset is being depreciated (sometimes called the useful life of the asset). @@ -10175,120 +12627,120 @@ declare module Excel { * @param endPeriod Is the ending period for which you want to calculate the depreciation, in the same units as Life. * @param factor Is the rate at which the balance declines, 2 (double-declining balance) if omitted. * @param noSwitch Switch to straight-line depreciation when depreciation is greater than the declining balance = FALSE or omitted; do not switch = TRUE. - * - * [Api set: ExcelApi 1.2] */ vdb(cost: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, salvage: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, life: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, startPeriod: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endPeriod: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, factor?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, noSwitch?: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the week number in the year. * + * [Api set: ExcelApi 1.2] + * * @param serialNumber Is the date-time code used by Microsoft Excel for date and time calculation. * @param returnType Is a number (1 or 2) that determines the type of the return value. - * - * [Api set: ExcelApi 1.2] */ weekNum(serialNumber: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, returnType?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a number from 1 to 7 identifying the day of the week of a date. * + * [Api set: ExcelApi 1.2] + * * @param serialNumber Is a number that represents a date. * @param returnType Is a number: for Sunday=1 through Saturday=7, use 1; for Monday=1 through Sunday=7, use 2; for Monday=0 through Sunday=6, use 3. - * - * [Api set: ExcelApi 1.2] */ weekday(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, returnType?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the Weibull distribution. * + * [Api set: ExcelApi 1.2] + * * @param x Is the value at which to evaluate the function, a nonnegative number. * @param alpha Is a parameter to the distribution, a positive number. * @param beta Is a parameter to the distribution, a positive number. * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability mass function, use FALSE. - * - * [Api set: ExcelApi 1.2] */ weibull_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, alpha: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, beta: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the serial number of the date before or after a specified number of workdays. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param days Is the number of nonweekend and non-holiday days before or after startDate. * @param holidays Is an optional array of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays. - * - * [Api set: ExcelApi 1.2] */ workDay(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, days: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, holidays?: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the serial number of the date before or after a specified number of workdays with custom weekend parameters. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param days Is the number of nonweekend and non-holiday days before or after startDate. * @param weekend Is a number or string specifying when weekends occur. * @param holidays Is an optional array of one or more serial date numbers to exclude from the working calendar, such as state and federal holidays and floating holidays. - * - * [Api set: ExcelApi 1.2] */ workDay_Intl(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, days: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, weekend?: number | string | Excel.Range | Excel.RangeReference | Excel.FunctionResult, holidays?: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the internal rate of return for a schedule of cash flows. * + * [Api set: ExcelApi 1.2] + * * @param values Is a series of cash flows that correspond to a schedule of payments in dates. * @param dates Is a schedule of payment dates that corresponds to the cash flow payments. * @param guess Is a number that you guess is close to the result of XIRR. - * - * [Api set: ExcelApi 1.2] */ xirr(values: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult, dates: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult, guess?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the net present value for a schedule of cash flows. * + * [Api set: ExcelApi 1.2] + * * @param rate Is the discount rate to apply to the cash flows. * @param values Is a series of cash flows that correspond to a schedule of payments in dates. * @param dates Is a schedule of payment dates that corresponds to the cash flow payments. - * - * [Api set: ExcelApi 1.2] */ xnpv(rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, values: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult, dates: number | string | Excel.Range | boolean | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns a logical 'Exclusive Or' of all arguments. * - * @param values List of parameters, whose elements are 1 to 254 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references. - * * [Api set: ExcelApi 1.2] + * + * @param values List of parameters, whose elements are 1 to 254 conditions you want to test that can be either TRUE or FALSE and can be logical values, arrays, or references. */ xor(...values: Array>): FunctionResult; /** * * Returns the year of a date, an integer in the range 1900 - 9999. * - * @param serialNumber Is a number in the date-time code used by Microsoft Excel. - * * [Api set: ExcelApi 1.2] + * + * @param serialNumber Is a number in the date-time code used by Microsoft Excel. */ year(serialNumber: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the year fraction representing the number of whole days between start_date and end_date. * + * [Api set: ExcelApi 1.2] + * * @param startDate Is a serial date number that represents the start date. * @param endDate Is a serial date number that represents the end date. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ yearFrac(startDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, endDate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the yield on a security that pays periodic interest. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param rate Is the security's annual coupon rate. @@ -10296,51 +12748,49 @@ declare module Excel { * @param redemption Is the security's redemption value per $100 face value. * @param frequency Is the number of coupon payments per year. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ yield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, frequency: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the annual yield for a discounted security. For example, a treasury bill. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param pr Is the security's price per $100 face value. * @param redemption Is the security's redemption value per $100 face value. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ yieldDisc(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, redemption: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the annual yield of a security that pays interest at maturity. * + * [Api set: ExcelApi 1.2] + * * @param settlement Is the security's settlement date, expressed as a serial date number. * @param maturity Is the security's maturity date, expressed as a serial date number. * @param issue Is the security's issue date, expressed as a serial date number. * @param rate Is the security's interest rate at date of issue. * @param pr Is the security's price per $100 face value. * @param basis Is the type of day count basis to use. - * - * [Api set: ExcelApi 1.2] */ yieldMat(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, issue: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, rate: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, basis?: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the one-tailed P-value of a z-test. * + * [Api set: ExcelApi 1.2] + * * @param array Is the array or range of data against which to test X. * @param x Is the value to test. * @param sigma Is the population (known) standard deviation. If omitted, the sample standard deviation is used. - * - * [Api set: ExcelApi 1.2] */ z_Test(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, sigma?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; toJSON(): {}; } - module ErrorCodes { + namespace ErrorCodes { var accessDenied: string; var apiNotFound: string; var generalException: string; @@ -10355,56 +12805,1382 @@ declare module Excel { var notImplemented: string; var unsupportedOperation: string; } -} -declare module Excel { - /** - * The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. - */ - class RequestContext extends OfficeExtension.ClientRequestContext { - constructor(url?: string); - workbook: Workbook; + module Interfaces { + /** An interface for updating data on the Worksheet object, for use in "worksheet.set({ ... })". */ + interface WorksheetUpdateData { + /** + * + * The display name of the worksheet. + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + /** + * + * The zero-based position of the worksheet within the workbook. + * + * [Api set: ExcelApi 1.1] + */ + position?: number; + /** + * + * The Visibility of the worksheet. + * + * [Api set: ExcelApi 1.1 for reading visibility; 1.2 for setting it.] + */ + visibility?: string; + } + /** An interface for updating data on the Range object, for use in "range.set({ ... })". */ + interface RangeUpdateData { + /** + * + * Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.RangeFormatUpdateData; + /** + * + * Represents if all columns of the current range are hidden. + * + * [Api set: ExcelApi 1.2] + */ + columnHidden?: boolean; + /** + * + * Represents the formula in A1-style notation. + * + * [Api set: ExcelApi 1.1] + */ + formulas?: Array>; + /** + * + * Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. + * + * [Api set: ExcelApi 1.1] + */ + formulasLocal?: Array>; + /** + * + * Represents the formula in R1C1-style notation. + * + * [Api set: ExcelApi 1.2] + */ + formulasR1C1?: Array>; + /** + * + * Represents Excel's number format code for the given cell. + * + * [Api set: ExcelApi 1.1] + */ + numberFormat?: Array>; + /** + * + * Represents if all rows of the current range are hidden. + * + * [Api set: ExcelApi 1.2] + */ + rowHidden?: boolean; + /** + * + * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.1] + */ + values?: Array>; + } + /** An interface for updating data on the RangeView object, for use in "rangeView.set({ ... })". */ + interface RangeViewUpdateData { + /** + * + * Represents the formula in A1-style notation. + * + * [Api set: ExcelApi 1.3] + */ + formulas?: Array>; + /** + * + * Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. + * + * [Api set: ExcelApi 1.3] + */ + formulasLocal?: Array>; + /** + * + * Represents the formula in R1C1-style notation. + * + * [Api set: ExcelApi 1.3] + */ + formulasR1C1?: Array>; + /** + * + * Represents Excel's number format code for the given cell. + * + * [Api set: ExcelApi 1.3] + */ + numberFormat?: Array>; + /** + * + * Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.3] + */ + values?: Array>; + } + /** An interface for updating data on the Setting object, for use in "setting.set({ ... })". */ + interface SettingUpdateData { + /** + * + * Represents the value stored for this setting. + * + * [Api set: ExcelApi 1.4] + */ + value?: any; + } + /** An interface for updating data on the NamedItem object, for use in "namedItem.set({ ... })". */ + interface NamedItemUpdateData { + /** + * + * Represents the comment associated with this name. + * + * [Api set: ExcelApi 1.4] + */ + comment?: string; + /** + * + * Specifies whether the object is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + visible?: boolean; + } + /** An interface for updating data on the Table object, for use in "table.set({ ... })". */ + interface TableUpdateData { + /** + * + * Indicates whether the first column contains special formatting. + * + * [Api set: ExcelApi 1.3] + */ + highlightFirstColumn?: boolean; + /** + * + * Indicates whether the last column contains special formatting. + * + * [Api set: ExcelApi 1.3] + */ + highlightLastColumn?: boolean; + /** + * + * Name of the table. + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + /** + * + * Indicates whether the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3] + */ + showBandedColumns?: boolean; + /** + * + * Indicates whether the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3] + */ + showBandedRows?: boolean; + /** + * + * Indicates whether the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row. + * + * [Api set: ExcelApi 1.3] + */ + showFilterButton?: boolean; + /** + * + * Indicates whether the header row is visible or not. This value can be set to show or remove the header row. + * + * [Api set: ExcelApi 1.1] + */ + showHeaders?: boolean; + /** + * + * Indicates whether the total row is visible or not. This value can be set to show or remove the total row. + * + * [Api set: ExcelApi 1.1] + */ + showTotals?: boolean; + /** + * + * Constant value that represents the Table style. Possible values are: TableStyleLight1 thru TableStyleLight21, TableStyleMedium1 thru TableStyleMedium28, TableStyleStyleDark1 thru TableStyleStyleDark11. A custom user-defined style present in the workbook can also be specified. + * + * [Api set: ExcelApi 1.1] + */ + style?: string; + } + /** An interface for updating data on the TableColumn object, for use in "tableColumn.set({ ... })". */ + interface TableColumnUpdateData { + /** + * + * Represents the name of the table column. + * + * [Api set: ExcelApi 1.1 for getting the name; 1.4 for setting it.] + */ + name?: string; + /** + * + * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.1] + */ + values?: Array>; + } + /** An interface for updating data on the TableRow object, for use in "tableRow.set({ ... })". */ + interface TableRowUpdateData { + /** + * + * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.1] + */ + values?: Array>; + } + /** An interface for updating data on the RangeFormat object, for use in "rangeFormat.set({ ... })". */ + interface RangeFormatUpdateData { + /** + * + * Returns the fill object defined on the overall range. + * + * [Api set: ExcelApi 1.1] + */ + fill?: Excel.Interfaces.RangeFillUpdateData; + /** + * + * Returns the font object defined on the overall range. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.RangeFontUpdateData; + /** + * + * Returns the format protection object for a range. + * + * [Api set: ExcelApi 1.2] + */ + protection?: Excel.Interfaces.FormatProtectionUpdateData; + /** + * + * Gets or sets the width of all colums within the range. If the column widths are not uniform, null will be returned. + * + * [Api set: ExcelApi 1.2] + */ + columnWidth?: number; + /** + * + * Represents the horizontal alignment for the specified object. See Excel.HorizontalAlignment for details. + * + * [Api set: ExcelApi 1.1] + */ + horizontalAlignment?: string; + /** + * + * Gets or sets the height of all rows in the range. If the row heights are not uniform null will be returned. + * + * [Api set: ExcelApi 1.2] + */ + rowHeight?: number; + /** + * + * Represents the vertical alignment for the specified object. See Excel.VerticalAlignment for details. + * + * [Api set: ExcelApi 1.1] + */ + verticalAlignment?: string; + /** + * + * Indicates if Excel wraps the text in the object. A null value indicates that the entire range doesn't have uniform wrap setting + * + * [Api set: ExcelApi 1.1] + */ + wrapText?: boolean; + } + /** An interface for updating data on the FormatProtection object, for use in "formatProtection.set({ ... })". */ + interface FormatProtectionUpdateData { + /** + * + * Indicates if Excel hides the formula for the cells in the range. A null value indicates that the entire range doesn't have uniform formula hidden setting. + * + * [Api set: ExcelApi 1.2] + */ + formulaHidden?: boolean; + /** + * + * Indicates if Excel locks the cells in the object. A null value indicates that the entire range doesn't have uniform lock setting. + * + * [Api set: ExcelApi 1.2] + */ + locked?: boolean; + } + /** An interface for updating data on the RangeFill object, for use in "rangeFill.set({ ... })". */ + interface RangeFillUpdateData { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * + * [Api set: ExcelApi 1.1] + */ + color?: string; + } + /** An interface for updating data on the RangeBorder object, for use in "rangeBorder.set({ ... })". */ + interface RangeBorderUpdateData { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.1] + */ + color?: string; + /** + * + * One of the constants of line style specifying the line style for the border. See Excel.BorderLineStyle for details. + * + * [Api set: ExcelApi 1.1] + */ + style?: string; + /** + * + * Specifies the weight of the border around a range. See Excel.BorderWeight for details. + * + * [Api set: ExcelApi 1.1] + */ + weight?: string; + } + /** An interface for updating data on the RangeFont object, for use in "rangeFont.set({ ... })". */ + interface RangeFontUpdateData { + /** + * + * Represents the bold status of font. + * + * [Api set: ExcelApi 1.1] + */ + bold?: boolean; + /** + * + * HTML color code representation of the text color. E.g. #FF0000 represents Red. + * + * [Api set: ExcelApi 1.1] + */ + color?: string; + /** + * + * Represents the italic status of the font. + * + * [Api set: ExcelApi 1.1] + */ + italic?: boolean; + /** + * + * Font name (e.g. "Calibri") + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + /** + * + * Font size. + * + * [Api set: ExcelApi 1.1] + */ + size?: number; + /** + * + * Type of underline applied to the font. See Excel.RangeUnderlineStyle for details. + * + * [Api set: ExcelApi 1.1] + */ + underline?: string; + } + /** An interface for updating data on the Chart object, for use in "chart.set({ ... })". */ + interface ChartUpdateData { + /** + * + * Represents chart axes. + * + * [Api set: ExcelApi 1.1] + */ + axes?: Excel.Interfaces.ChartAxesUpdateData; + /** + * + * Represents the datalabels on the chart. + * + * [Api set: ExcelApi 1.1] + */ + dataLabels?: Excel.Interfaces.ChartDataLabelsUpdateData; + /** + * + * Encapsulates the format properties for the chart area. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartAreaFormatUpdateData; + /** + * + * Represents the legend for the chart. + * + * [Api set: ExcelApi 1.1] + */ + legend?: Excel.Interfaces.ChartLegendUpdateData; + /** + * + * Represents the title of the specified chart, including the text, visibility, position and formating of the title. + * + * [Api set: ExcelApi 1.1] + */ + title?: Excel.Interfaces.ChartTitleUpdateData; + /** + * + * Represents the height, in points, of the chart object. + * + * [Api set: ExcelApi 1.1] + */ + height?: number; + /** + * + * The distance, in points, from the left side of the chart to the worksheet origin. + * + * [Api set: ExcelApi 1.1] + */ + left?: number; + /** + * + * Represents the name of a chart object. + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + /** + * + * Represents the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart). + * + * [Api set: ExcelApi 1.1] + */ + top?: number; + /** + * + * Represents the width, in points, of the chart object. + * + * [Api set: ExcelApi 1.1] + */ + width?: number; + } + /** An interface for updating data on the ChartAreaFormat object, for use in "chartAreaFormat.set({ ... })". */ + interface ChartAreaFormatUpdateData { + /** + * + * Represents the font attributes (font name, font size, color, etc.) for the current object. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + } + /** An interface for updating data on the ChartSeries object, for use in "chartSeries.set({ ... })". */ + interface ChartSeriesUpdateData { + /** + * + * Represents the formatting of a chart series, which includes fill and line formatting. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartSeriesFormatUpdateData; + /** + * + * Represents the name of a series in a chart. + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + } + /** An interface for updating data on the ChartSeriesFormat object, for use in "chartSeriesFormat.set({ ... })". */ + interface ChartSeriesFormatUpdateData { + /** + * + * Represents line formatting. + * + * [Api set: ExcelApi 1.1] + */ + line?: Excel.Interfaces.ChartLineFormatUpdateData; + } + /** An interface for updating data on the ChartAxes object, for use in "chartAxes.set({ ... })". */ + interface ChartAxesUpdateData { + /** + * + * Represents the category axis in a chart. + * + * [Api set: ExcelApi 1.1] + */ + categoryAxis?: Excel.Interfaces.ChartAxisUpdateData; + /** + * + * Represents the series axis of a 3-dimensional chart. + * + * [Api set: ExcelApi 1.1] + */ + seriesAxis?: Excel.Interfaces.ChartAxisUpdateData; + /** + * + * Represents the value axis in an axis. + * + * [Api set: ExcelApi 1.1] + */ + valueAxis?: Excel.Interfaces.ChartAxisUpdateData; + } + /** An interface for updating data on the ChartAxis object, for use in "chartAxis.set({ ... })". */ + interface ChartAxisUpdateData { + /** + * + * Represents the formatting of a chart object, which includes line and font formatting. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartAxisFormatUpdateData; + /** + * + * Returns a gridlines object that represents the major gridlines for the specified axis. + * + * [Api set: ExcelApi 1.1] + */ + majorGridlines?: Excel.Interfaces.ChartGridlinesUpdateData; + /** + * + * Returns a Gridlines object that represents the minor gridlines for the specified axis. + * + * [Api set: ExcelApi 1.1] + */ + minorGridlines?: Excel.Interfaces.ChartGridlinesUpdateData; + /** + * + * Represents the axis title. + * + * [Api set: ExcelApi 1.1] + */ + title?: Excel.Interfaces.ChartAxisTitleUpdateData; + /** + * + * Represents the interval between two major tick marks. Can be set to a numeric value or an empty string. The returned value is always a number. + * + * [Api set: ExcelApi 1.1] + */ + majorUnit?: any; + /** + * + * Represents the maximum value on the value axis. Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number. + * + * [Api set: ExcelApi 1.1] + */ + maximum?: any; + /** + * + * Represents the minimum value on the value axis. Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number. + * + * [Api set: ExcelApi 1.1] + */ + minimum?: any; + /** + * + * Represents the interval between two minor tick marks. "Can be set to a numeric value or an empty string (for automatic axis values). The returned value is always a number. + * + * [Api set: ExcelApi 1.1] + */ + minorUnit?: any; + } + /** An interface for updating data on the ChartAxisFormat object, for use in "chartAxisFormat.set({ ... })". */ + interface ChartAxisFormatUpdateData { + /** + * + * Represents the font attributes (font name, font size, color, etc.) for a chart axis element. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + /** + * + * Represents chart line formatting. + * + * [Api set: ExcelApi 1.1] + */ + line?: Excel.Interfaces.ChartLineFormatUpdateData; + } + /** An interface for updating data on the ChartAxisTitle object, for use in "chartAxisTitle.set({ ... })". */ + interface ChartAxisTitleUpdateData { + /** + * + * Represents the formatting of chart axis title. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartAxisTitleFormatUpdateData; + /** + * + * Represents the axis title. + * + * [Api set: ExcelApi 1.1] + */ + text?: string; + /** + * + * A boolean that specifies the visibility of an axis title. + * + * [Api set: ExcelApi 1.1] + */ + visible?: boolean; + } + /** An interface for updating data on the ChartAxisTitleFormat object, for use in "chartAxisTitleFormat.set({ ... })". */ + interface ChartAxisTitleFormatUpdateData { + /** + * + * Represents the font attributes, such as font name, font size, color, etc. of chart axis title object. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + } + /** An interface for updating data on the ChartDataLabels object, for use in "chartDataLabels.set({ ... })". */ + interface ChartDataLabelsUpdateData { + /** + * + * Represents the format of chart data labels, which includes fill and font formatting. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartDataLabelFormatUpdateData; + /** + * + * DataLabelPosition value that represents the position of the data label. See Excel.ChartDataLabelPosition for details. + * + * [Api set: ExcelApi 1.1] + */ + position?: string; + /** + * + * String representing the separator used for the data labels on a chart. + * + * [Api set: ExcelApi 1.1] + */ + separator?: string; + /** + * + * Boolean value representing if the data label bubble size is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showBubbleSize?: boolean; + /** + * + * Boolean value representing if the data label category name is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showCategoryName?: boolean; + /** + * + * Boolean value representing if the data label legend key is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showLegendKey?: boolean; + /** + * + * Boolean value representing if the data label percentage is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showPercentage?: boolean; + /** + * + * Boolean value representing if the data label series name is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showSeriesName?: boolean; + /** + * + * Boolean value representing if the data label value is visible or not. + * + * [Api set: ExcelApi 1.1] + */ + showValue?: boolean; + } + /** An interface for updating data on the ChartDataLabelFormat object, for use in "chartDataLabelFormat.set({ ... })". */ + interface ChartDataLabelFormatUpdateData { + /** + * + * Represents the font attributes (font name, font size, color, etc.) for a chart data label. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + } + /** An interface for updating data on the ChartGridlines object, for use in "chartGridlines.set({ ... })". */ + interface ChartGridlinesUpdateData { + /** + * + * Represents the formatting of chart gridlines. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartGridlinesFormatUpdateData; + /** + * + * Boolean value representing if the axis gridlines are visible or not. + * + * [Api set: ExcelApi 1.1] + */ + visible?: boolean; + } + /** An interface for updating data on the ChartGridlinesFormat object, for use in "chartGridlinesFormat.set({ ... })". */ + interface ChartGridlinesFormatUpdateData { + /** + * + * Represents chart line formatting. + * + * [Api set: ExcelApi 1.1] + */ + line?: Excel.Interfaces.ChartLineFormatUpdateData; + } + /** An interface for updating data on the ChartLegend object, for use in "chartLegend.set({ ... })". */ + interface ChartLegendUpdateData { + /** + * + * Represents the formatting of a chart legend, which includes fill and font formatting. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartLegendFormatUpdateData; + /** + * + * Boolean value for whether the chart legend should overlap with the main body of the chart. + * + * [Api set: ExcelApi 1.1] + */ + overlay?: boolean; + /** + * + * Represents the position of the legend on the chart. See Excel.ChartLegendPosition for details. + * + * [Api set: ExcelApi 1.1] + */ + position?: string; + /** + * + * A boolean value the represents the visibility of a ChartLegend object. + * + * [Api set: ExcelApi 1.1] + */ + visible?: boolean; + } + /** An interface for updating data on the ChartLegendFormat object, for use in "chartLegendFormat.set({ ... })". */ + interface ChartLegendFormatUpdateData { + /** + * + * Represents the font attributes such as font name, font size, color, etc. of a chart legend. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + } + /** An interface for updating data on the ChartTitle object, for use in "chartTitle.set({ ... })". */ + interface ChartTitleUpdateData { + /** + * + * Represents the formatting of a chart title, which includes fill and font formatting. + * + * [Api set: ExcelApi 1.1] + */ + format?: Excel.Interfaces.ChartTitleFormatUpdateData; + /** + * + * Boolean value representing if the chart title will overlay the chart or not. + * + * [Api set: ExcelApi 1.1] + */ + overlay?: boolean; + /** + * + * Represents the title text of a chart. + * + * [Api set: ExcelApi 1.1] + */ + text?: string; + /** + * + * A boolean value the represents the visibility of a chart title object. + * + * [Api set: ExcelApi 1.1] + */ + visible?: boolean; + } + /** An interface for updating data on the ChartTitleFormat object, for use in "chartTitleFormat.set({ ... })". */ + interface ChartTitleFormatUpdateData { + /** + * + * Represents the font attributes (font name, font size, color, etc.) for an object. + * + * [Api set: ExcelApi 1.1] + */ + font?: Excel.Interfaces.ChartFontUpdateData; + } + /** An interface for updating data on the ChartLineFormat object, for use in "chartLineFormat.set({ ... })". */ + interface ChartLineFormatUpdateData { + /** + * + * HTML color code representing the color of lines in the chart. + * + * [Api set: ExcelApi 1.1] + */ + color?: string; + } + /** An interface for updating data on the ChartFont object, for use in "chartFont.set({ ... })". */ + interface ChartFontUpdateData { + /** + * + * Represents the bold status of font. + * + * [Api set: ExcelApi 1.1] + */ + bold?: boolean; + /** + * + * HTML color code representation of the text color. E.g. #FF0000 represents Red. + * + * [Api set: ExcelApi 1.1] + */ + color?: string; + /** + * + * Represents the italic status of the font. + * + * [Api set: ExcelApi 1.1] + */ + italic?: boolean; + /** + * + * Font name (e.g. "Calibri") + * + * [Api set: ExcelApi 1.1] + */ + name?: string; + /** + * + * Size of the font (e.g. 11) + * + * [Api set: ExcelApi 1.1] + */ + size?: number; + /** + * + * Type of underline applied to the font. See Excel.ChartUnderlineStyle for details. + * + * [Api set: ExcelApi 1.1] + */ + underline?: string; + } + /** An interface for updating data on the PivotTable object, for use in "pivotTable.set({ ... })". */ + interface PivotTableUpdateData { + /** + * + * Name of the PivotTable. + * + * [Api set: ExcelApi 1.3] + */ + name?: string; + } + /** An interface for updating data on the ConditionalFormat object, for use in "conditionalFormat.set({ ... })". */ + interface ConditionalFormatUpdateData { + /** + * + * Returns the cell value conditional format properties if the current conditional format is a CellValue type. + For example to format all cells between 5 and 10. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + cellValue?: Excel.Interfaces.CellValueConditionalFormatUpdateData; + /** + * + * Returns the cell value conditional format properties if the current conditional format is a CellValue type. + For example to format all cells between 5 and 10. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + cellValueOrNullObject?: Excel.Interfaces.CellValueConditionalFormatUpdateData; + /** + * + * Returns the ColorScale conditional format properties if the current conditional format is an ColorScale type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + colorScale?: Excel.Interfaces.ColorScaleConditionalFormatUpdateData; + /** + * + * Returns the ColorScale conditional format properties if the current conditional format is an ColorScale type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + colorScaleOrNullObject?: Excel.Interfaces.ColorScaleConditionalFormatUpdateData; + /** + * + * Returns the custom conditional format properties if the current conditional format is a custom type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + custom?: Excel.Interfaces.CustomConditionalFormatUpdateData; + /** + * + * Returns the custom conditional format properties if the current conditional format is a custom type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + customOrNullObject?: Excel.Interfaces.CustomConditionalFormatUpdateData; + /** + * + * Returns the data bar properties if the current conditional format is a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + dataBar?: Excel.Interfaces.DataBarConditionalFormatUpdateData; + /** + * + * Returns the data bar properties if the current conditional format is a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + dataBarOrNullObject?: Excel.Interfaces.DataBarConditionalFormatUpdateData; + /** + * + * Returns the IconSet conditional format properties if the current conditional format is an IconSet type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + iconSet?: Excel.Interfaces.IconSetConditionalFormatUpdateData; + /** + * + * Returns the IconSet conditional format properties if the current conditional format is an IconSet type. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + iconSetOrNullObject?: Excel.Interfaces.IconSetConditionalFormatUpdateData; + /** + * + * Returns the preset criteria conditional format such as above average/below average/unique values/contains blank/nonblank/error/noerror properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + preset?: Excel.Interfaces.PresetCriteriaConditionalFormatUpdateData; + /** + * + * Returns the preset criteria conditional format such as above average/below average/unique values/contains blank/nonblank/error/noerror properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + presetOrNullObject?: Excel.Interfaces.PresetCriteriaConditionalFormatUpdateData; + /** + * + * Returns the specific text conditional format properties if the current conditional format is a text type. + For example to format cells matching the word "Text". + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + textComparison?: Excel.Interfaces.TextConditionalFormatUpdateData; + /** + * + * Returns the specific text conditional format properties if the current conditional format is a text type. + For example to format cells matching the word "Text". + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + textComparisonOrNullObject?: Excel.Interfaces.TextConditionalFormatUpdateData; + /** + * + * Returns the Top/Bottom conditional format properties if the current conditional format is an TopBottom type. + For example to format the top 10% or bottom 10 items. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + topBottom?: Excel.Interfaces.TopBottomConditionalFormatUpdateData; + /** + * + * Returns the Top/Bottom conditional format properties if the current conditional format is an TopBottom type. + For example to format the top 10% or bottom 10 items. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + topBottomOrNullObject?: Excel.Interfaces.TopBottomConditionalFormatUpdateData; + /** + * + * The priority (or index) within the conditional format collection that this conditional format currently exists in. Changing this also + changes other conditional formats' priorities, to allow for a contiguous priority order. + Use a negative priority to begin from the back. + Priorities greater than than bounds will get and set to the maximum (or minimum if negative) priority. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + priority?: number; + /** + * + * If the conditions of this conditional format are met, no lower-priority formats shall take effect on that cell. + Null on databars, icon sets, and colorscales as there's no concept of StopIfTrue for these + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + stopIfTrue?: boolean; + } + /** An interface for updating data on the DataBarConditionalFormat object, for use in "dataBarConditionalFormat.set({ ... })". */ + interface DataBarConditionalFormatUpdateData { + /** + * + * Representation of all values to the left of the axis in an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + negativeFormat?: Excel.Interfaces.ConditionalDataBarNegativeFormatUpdateData; + /** + * + * Representation of all values to the right of the axis in an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + positiveFormat?: Excel.Interfaces.ConditionalDataBarPositiveFormatUpdateData; + /** + * + * HTML color code representing the color of the Axis line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "" (empty string) if no axis is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + axisColor?: string; + /** + * + * Representation of how the axis is determined for an Excel data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + axisFormat?: string; + /** + * + * Represents the direction that the data bar graphic should be based on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + barDirection?: string; + /** + * + * The rule for what consistutes the lower bound (and how to calculate it, if applicable) for a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + lowerBoundRule?: Excel.ConditionalDataBarRule; + /** + * + * If true, hides the values from the cells where the data bar is applied. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + showDataBarOnly?: boolean; + /** + * + * The rule for what constitutes the upper bound (and how to calculate it, if applicable) for a data bar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + upperBoundRule?: Excel.ConditionalDataBarRule; + } + /** An interface for updating data on the ConditionalDataBarPositiveFormat object, for use in "conditionalDataBarPositiveFormat.set({ ... })". */ + interface ConditionalDataBarPositiveFormatUpdateData { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "" (empty string) if no border is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + borderColor?: string; + /** + * + * HTML color code representing the fill color, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + fillColor?: string; + /** + * + * Boolean representation of whether or not the DataBar has a gradient. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + gradientFill?: boolean; + } + /** An interface for updating data on the ConditionalDataBarNegativeFormat object, for use in "conditionalDataBarNegativeFormat.set({ ... })". */ + interface ConditionalDataBarNegativeFormatUpdateData { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + "Empty String" if no border is present or set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + borderColor?: string; + /** + * + * HTML color code representing the fill color, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + fillColor?: string; + /** + * + * Boolean representation of whether or not the negative DataBar has the same border color as the positive DataBar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + matchPositiveBorderColor?: boolean; + /** + * + * Boolean representation of whether or not the negative DataBar has the same fill color as the positive DataBar. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + matchPositiveFillColor?: boolean; + } + /** An interface for updating data on the CustomConditionalFormat object, for use in "customConditionalFormat.set({ ... })". */ + interface CustomConditionalFormatUpdateData { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + format?: Excel.Interfaces.ConditionalRangeFormatUpdateData; + /** + * + * Represents the Rule object on this conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule?: Excel.Interfaces.ConditionalFormatRuleUpdateData; + } + /** An interface for updating data on the ConditionalFormatRule object, for use in "conditionalFormatRule.set({ ... })". */ + interface ConditionalFormatRuleUpdateData { + /** + * + * The formula, if required, to evaluate the conditional format rule on. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formula?: string; + /** + * + * The formula, if required, to evaluate the conditional format rule on in the user's language. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formulaLocal?: string; + /** + * + * The formula, if required, to evaluate the conditional format rule on in R1C1-style notation. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + formulaR1C1?: string; + } + /** An interface for updating data on the IconSetConditionalFormat object, for use in "iconSetConditionalFormat.set({ ... })". */ + interface IconSetConditionalFormatUpdateData { + /** + * + * An array of Criteria and IconSets for the rules and potential custom icons for conditional icons. Note that for the first criterion only the custom icon can be modified, while type, formula and operator will be ignored when set. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + criteria?: Array; + /** + * + * If true, reverses the icon orders for the IconSet. Note that this cannot be set if custom icons are used. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + reverseIconOrder?: boolean; + /** + * + * If true, hides the values and only shows icons. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + showIconOnly?: boolean; + /** + * + * If set, displays the IconSet option for the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + style?: string; + } + /** An interface for updating data on the ColorScaleConditionalFormat object, for use in "colorScaleConditionalFormat.set({ ... })". */ + interface ColorScaleConditionalFormatUpdateData { + /** + * + * The criteria of the color scale. Midpoint is optional when using a two point color scale. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + criteria?: Excel.ConditionalColorScaleCriteria; + } + /** An interface for updating data on the TopBottomConditionalFormat object, for use in "topBottomConditionalFormat.set({ ... })". */ + interface TopBottomConditionalFormatUpdateData { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + format?: Excel.Interfaces.ConditionalRangeFormatUpdateData; + /** + * + * The criteria of the Top/Bottom conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule?: Excel.ConditionalTopBottomRule; + } + /** An interface for updating data on the PresetCriteriaConditionalFormat object, for use in "presetCriteriaConditionalFormat.set({ ... })". */ + interface PresetCriteriaConditionalFormatUpdateData { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + format?: Excel.Interfaces.ConditionalRangeFormatUpdateData; + /** + * + * The rule of the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule?: Excel.ConditionalPresetCriteriaRule; + } + /** An interface for updating data on the TextConditionalFormat object, for use in "textConditionalFormat.set({ ... })". */ + interface TextConditionalFormatUpdateData { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + format?: Excel.Interfaces.ConditionalRangeFormatUpdateData; + /** + * + * The rule of the conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule?: Excel.ConditionalTextComparisonRule; + } + /** An interface for updating data on the CellValueConditionalFormat object, for use in "cellValueConditionalFormat.set({ ... })". */ + interface CellValueConditionalFormatUpdateData { + /** + * + * Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + format?: Excel.Interfaces.ConditionalRangeFormatUpdateData; + /** + * + * Represents the Rule object on this conditional format. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + rule?: Excel.ConditionalCellValueRule; + } + /** An interface for updating data on the ConditionalRangeFormat object, for use in "conditionalRangeFormat.set({ ... })". */ + interface ConditionalRangeFormatUpdateData { + /** + * + * Represents Excel's number format code for the given range. Cleared if null is passed in. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + numberFormat?: any; + } + /** An interface for updating data on the ConditionalRangeFont object, for use in "conditionalRangeFont.set({ ... })". */ + interface ConditionalRangeFontUpdateData { + /** + * + * Represents the bold status of font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + bold?: boolean; + /** + * + * HTML color code representation of the text color. E.g. #FF0000 represents Red. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color?: string; + /** + * + * Represents the italic status of the font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + italic?: boolean; + /** + * + * Represents the strikethrough status of the font. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + strikethrough?: boolean; + /** + * + * Type of underline applied to the font. See Excel.ConditionalRangeFontUnderlineStyle for details. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + underline?: string; + } + /** An interface for updating data on the ConditionalRangeFill object, for use in "conditionalRangeFill.set({ ... })". */ + interface ConditionalRangeFillUpdateData { + /** + * + * HTML color code representing the color of the fill, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color?: string; + } + /** An interface for updating data on the ConditionalRangeBorder object, for use in "conditionalRangeBorder.set({ ... })". */ + interface ConditionalRangeBorderUpdateData { + /** + * + * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + color?: string; + /** + * + * One of the constants of line style specifying the line style for the border. See Excel.BorderLineStyle for details. + * + * [Api set: ExcelApi 1.6 (PREVIEW)] + */ + style?: string; + } } - /** - * Executes a batch script that performs actions on the Excel object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; - /** - * Executes a batch script that performs actions on the Excel object model, using a new remote RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. - * @param requestInfo - The URL of the remote workbook and the request headers to be sent. - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; - /** - * Executes a batch script that performs actions on the Excel object model, using the RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. - * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; - /** - * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. - * @param requestInfo - The URL of the remote workbook and the request headers to be sent. - * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; - /** - * Executes a batch script that performs actions on the Excel object model, using the RequestContext of previously-created API objects. - * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; - /** - * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of previously-created API objects. - * @param requestInfo - The URL of the remote workbook and the request headers to be sent. - * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". - * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. - */ - function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; } - //////////////////////////////////////////////////////////////// //////////////////////// End Excel APIs //////////////////////// //////////////////////////////////////////////////////////////// @@ -10418,10 +14194,9 @@ declare module Excel { //////////////////////////////////////////////////////////////// -//////////////////////// Begin Word APIs /////////////////////// +/////////////////////// Begin Word APIs //////////////////////// //////////////////////////////////////////////////////////////// - declare namespace Word { /** * @@ -15825,11 +19600,8 @@ declare module Word { } - - - //////////////////////////////////////////////////////////////// -///////////////////////// End Word APIs //////////////////////// +//////////////////////// End Word APIs ///////////////////////// //////////////////////////////////////////////////////////////// diff --git a/types/office-js/office-js-tests.ts b/types/office-js/office-js-tests.ts index 768ed7ae5d..d5a874693a 100644 --- a/types/office-js/office-js-tests.ts +++ b/types/office-js/office-js-tests.ts @@ -6,64 +6,64 @@ Copyright (c) Microsoft Corporation function test_excel() { - + // Range - Excel.run(function(ctx) { + Excel.run(function (ctx) { var range = ctx.workbook.getSelectedRange().load("values"); return ctx.sync() - .then(function() { + .then(function () { var vals = range.values; - for (var i = 0; i < vals.length; i++){ - for (var j = 0; j < vals[i].length; j++){ + for (var i = 0; i < vals.length; i++) { + for (var j = 0; j < vals[i].length; j++) { vals[i][j] = vals[i][j].toUpperCase(); } } range.values = vals; }) - .then(ctx.sync); + .then(ctx.sync); }).catch(function (error) { console.log(error); }); - - + + // Chart Excel.run(function (ctx) { var sheet = ctx.workbook.worksheets.getItem("Sheet1"); - + var range = sheet.getRange("A1:B3"); range.values = [ ["", "Gender"], ["Male", 12], ["Female", 14] ]; - - var chart = sheet.charts.add("pie", range, "auto"); - + + var chart = sheet.charts.add(Excel.ChartType._3DColumn, range, "auto"); + chart.format.fill.setSolidColor("F8F8FF"); - + chart.title.text = "Class Demographics"; chart.title.format.font.bold = true; chart.title.format.font.size = 18; chart.title.format.font.color = "568568"; - + chart.legend.position = "right"; chart.legend.format.font.name = "Algerian"; chart.legend.format.font.size = 13; - + chart.dataLabels.showPercentage = true; chart.dataLabels.format.font.size = 15; chart.dataLabels.format.font.color = "444444"; - + var points = chart.series.getItemAt(0).points; points.getItemAt(0).format.fill.setSolidColor("8FBC8F"); points.getItemAt(1).format.fill.setSolidColor("D87093"); - + return ctx.sync(); }).catch(function (error) { console.log(error); }); - - + + // Table Excel.run(function (ctx) { var rows = ctx.workbook.tables.getItem("Table1").rows.load("values"); @@ -71,77 +71,95 @@ function test_excel() { .then(function () { var largestRow = 0; var largestValue = 0; - - for (var i = 0; i < rows.items.length; i++){ - if (rows.items[i].values[0][1] > largestValue){ + + for (var i = 0; i < rows.items.length; i++) { + if (rows.items[i].values[0][1] > largestValue) { largestRow = i; largestValue = rows.items[i].values[0][1]; } } - + var largestRowRng = rows.getItemAt(largestRow).getRange(); largestRowRng.format.fill.color = "#ff0000"; - + }) - .then(ctx.sync); + .then(ctx.sync); }).catch(function (error) { console.log(error); }); - + + + // Object.set + Excel.run(ctx => { + const range = ctx.workbook.getSelectedRange(); + range.set({ + values: [[1]], + format: { + font: { + bold: true + }, + fill: { + color: "red" + } + } + }); + + return ctx.sync(); + }).catch(console.log); } function test_word() { - + // Search Word.run(function (context) { - + // Create a proxy object for the document body. var body = context.document.body; - + // Setup the search options. var options = Word.SearchOptions.newObject(context); options.matchCase = false - + // Queue a commmand to search the document. var searchResults = context.document.body.search('video', options); - + // Queue a commmand to load the results. context.load(searchResults, 'text, font'); - + // Synchronize the document state by executing the queued-up commands, // and return a promise to indicate task completion. return context.sync().then(function () { - var results = 'Found count: ' + searchResults.items.length + - '; we highlighted the results.'; - + var results = 'Found count: ' + searchResults.items.length + + '; we highlighted the results.'; + // Queue a command to change the font for each found item. for (var i = 0; i < searchResults.items.length; i++) { - searchResults.items[i].font.color = '#FF0000' // Change color to Red - searchResults.items[i].font.highlightColor = '#FFFF00'; - searchResults.items[i].font.bold = true; + searchResults.items[i].font.color = '#FF0000' // Change color to Red + searchResults.items[i].font.highlightColor = '#FFFF00'; + searchResults.items[i].font.bold = true; } - + // Synchronize the document state by executing the queued-up commands, // and return a promise to indicate task completion. return context.sync().then(function () { console.log(results); - }); - }); + }); + }); }) - .catch(function (error) { - console.log('Error: ' + JSON.stringify(error)); - if (error instanceof OfficeExtension.Error) { - console.log('Debug info: ' + JSON.stringify(error.debugInfo)); - } - }); + .catch(function (error) { + console.log('Error: ' + JSON.stringify(error)); + if (error instanceof OfficeExtension.Error) { + console.log('Debug info: ' + JSON.stringify(error.debugInfo)); + } + }); + - // Content control Word.run(function (context) { - + // Create a proxy range object for the current selection. var range = context.document.getSelection(); - + // Queue a commmand to create the content control. var myContentControl = range.insertContentControl(); myContentControl.tag = 'Customer-Address'; @@ -150,84 +168,84 @@ function test_word() { myContentControl.insertText('One Microsoft Way, Redmond, WA 98052', 'replace'); myContentControl.cannotEdit = true; myContentControl.appearance = 'tags'; - + // Queue a command to load the id property for the content control you created. context.load(myContentControl, 'id'); - + // Synchronize the document state by executing the queued-up commands, // and return a promise to indicate task completion. return context.sync().then(function () { console.log('Created content control with id: ' + myContentControl.id); - }); + }); }) - .catch(function (error) { - console.log('Error: ' + JSON.stringify(error)); - if (error instanceof OfficeExtension.Error) { - console.log('Debug info: ' + JSON.stringify(error.debugInfo)); - } - }); + .catch(function (error) { + console.log('Error: ' + JSON.stringify(error)); + if (error instanceof OfficeExtension.Error) { + console.log('Debug info: ' + JSON.stringify(error.debugInfo)); + } + }); - // Body.insertInlinePictureFromBase64 Word 1.1 - Word.run(function(context) { - - // Create a proxy body object. - var body = context.document.body; + // Body.insertInlinePictureFromBase64 Word 1.1 + Word.run(function (context) { - // Queue a command to insert the image into the document. - var image = body.insertInlinePictureFromBase64('', Word.InsertLocation.start); - - // Queue a command to select the image. - image.select(); - - // Synchronize the document state by executing the queued commands, - // and returning a promise to indicate task completion. - return context.sync() - }) - .catch(function(error) { - console.log('Error: ' + JSON.stringify(error)); - if (error instanceof OfficeExtension.Error) { - console.log('Debug info: ' + JSON.stringify(error.debugInfo)); - } - }); - - // Body.insertInlinePictureFromBase64 Word 1.2 - Word.run((context) => { + // Create a proxy body object. + var body = context.document.body; - // Create a proxy object for the range at the current selection. - var imageRange = context.document.getSelection(); + // Queue a command to insert the image into the document. + var image = body.insertInlinePictureFromBase64('', Word.InsertLocation.start); - // Load the selected range. - context.load(imageRange, 'text'); + // Queue a command to select the image. + image.select(); - // Synchronize the document state by executing the queued commands, - // and return a promise to indicate task completion. - return context.sync() - .then(() => { + // Synchronize the document state by executing the queued commands, + // and returning a promise to indicate task completion. + return context.sync() + }) + .catch(function (error) { + console.log('Error: ' + JSON.stringify(error)); + if (error instanceof OfficeExtension.Error) { + console.log('Debug info: ' + JSON.stringify(error.debugInfo)); + } + }); - // Queue a command to insert the image into the document. - var insertedImage = imageRange.insertInlinePictureFromBase64('', Word.InsertLocation.replace); + // Body.insertInlinePictureFromBase64 Word 1.2 + Word.run((context) => { - // Queue a command to navigate the UI to the insert picture. - insertedImage.select(); + // Create a proxy object for the range at the current selection. + var imageRange = context.document.getSelection(); - // Queue an indefinite number of commands to insert paragraphs - // based on the number of callouts added to the image. - if (this._calloutNumber > 0) { - var lastParagraph = insertedImage.insertParagraph('Here are your callout descriptions:', Word.InsertLocation.after) as Word.Paragraph; + // Load the selected range. + context.load(imageRange, 'text'); - for (var i = 0; i < this._calloutNumber; i++) { - lastParagraph = lastParagraph.insertParagraph((i + 1) + ') [enter callout description].', Word.InsertLocation.after); - } - } - }) - // Synchronize the document state by executing the queued commands. - .then(context.sync); - }) - .catch((error) => { - console.log('Error: ' + JSON.stringify(error)); - if (error instanceof OfficeExtension.Error) { - console.log('Debug info: ' + JSON.stringify(error.debugInfo)); - } - }); + // Synchronize the document state by executing the queued commands, + // and return a promise to indicate task completion. + return context.sync() + .then(() => { + + // Queue a command to insert the image into the document. + var insertedImage = imageRange.insertInlinePictureFromBase64('', Word.InsertLocation.replace); + + // Queue a command to navigate the UI to the insert picture. + insertedImage.select(); + + // Queue an indefinite number of commands to insert paragraphs + // based on the number of callouts added to the image. + if (this._calloutNumber > 0) { + var lastParagraph = insertedImage.insertParagraph('Here are your callout descriptions:', Word.InsertLocation.after) as Word.Paragraph; + + for (var i = 0; i < this._calloutNumber; i++) { + lastParagraph = lastParagraph.insertParagraph((i + 1) + ') [enter callout description].', Word.InsertLocation.after); + } + } + }) + // Synchronize the document state by executing the queued commands. + .then(context.sync); + }) + .catch((error) => { + console.log('Error: ' + JSON.stringify(error)); + if (error instanceof OfficeExtension.Error) { + console.log('Debug info: ' + JSON.stringify(error.debugInfo)); + } + }); } diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 2b721ab7ca..577e2f485a 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for OpenLayers v4.0.1 +// Type definitions for OpenLayers v4.1.0 // Project: http://openlayers.org/ -// Definitions by: Olivier Sechet +// Definitions by: Olivier Sechet , Guilhem Brouat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) @@ -4919,28 +4919,28 @@ declare module ol { * @param {ol.proj.Projection=} opt_projection Projection. */ constructor(type: ol.interaction.DragAndDropEventType, file: File, opt_features?: ol.Feature[], opt_projection?: ol.proj.Projection); - + /** * The features parsed from dropped data. * @type {Array.|undefined} * @api stable */ features: ol.Feature[]; - + /** * The dropped file. * @type {File} * @api stable */ file: File; - + /** * The feature projection. * @type {ol.proj.Projection|undefined} * @api */ projection: ol.proj.Projection; - + } } @@ -5023,7 +5023,7 @@ declare module ol { * @implements {oli.DragBoxEvent} */ constructor(type: string, coordinate: ol.Coordinate, mapBrowserEvent: ol.MapBrowserEvent); - + /** * The coordinate of the drag event. * @const @@ -5031,14 +5031,14 @@ declare module ol { * @api stable */ coordinate: ol.Coordinate; - + /** * @const * @type {ol.MapBrowserEvent} * @api */ mapBrowserEvent: ol.MapBrowserEvent; - + } } @@ -5195,14 +5195,14 @@ declare module ol { * @param {ol.Feature} feature The feature drawn. */ constructor(type: ol.interaction.DrawEventType, feature: ol.Feature); - + /** * The feature being drawn. * @type {ol.Feature} * @api stable */ feature: ol.Feature; - + } } @@ -5255,6 +5255,15 @@ declare module ol { */ extend(feature: ol.Feature): void; + /** + * Create a `geometryFunction` that will create a box-shaped polygon (aligned + * with the coordinate system axes). Use this with the draw interaction and + * `type: 'Circle'` to return a box instead of a circle geometry. + * @return {ol.DrawGeometryFunctionType} Function that draws a box-shaped polygon. + * @api + */ + static createBox(): ol.DrawGeometryFunctionType; + /** * Create a `geometryFunction` for `mode: 'Circle'` that will create a regular * polygon with a user specified number of sides and start angle instead of an @@ -5491,21 +5500,21 @@ declare module ol { * {@link ol.MapBrowserPointerEvent}. */ constructor(type: ol.ModifyEventType, features: ol.Collection, mapBrowserPointerEvent: ol.MapBrowserPointerEvent); - + /** * The features being modified. * @type {ol.Collection.} * @api */ features: ol.Collection; - + /** * Associated {@link ol.MapBrowserEvent}. * @type {ol.MapBrowserEvent} * @api */ mapBrowserEvent: ol.MapBrowserEvent; - + } } @@ -5713,28 +5722,28 @@ declare module ol { * @constructor */ constructor(type: string, selected: ol.Feature[], deselected: ol.Feature[], mapBrowserEvent: ol.MapBrowserEvent); - + /** * Selected features array. * @type {Array.} * @api */ selected: ol.Feature[]; - + /** * Deselected features array. * @type {Array.} * @api */ deselected: ol.Feature[]; - + /** * Associated {@link ol.MapBrowserEvent}. * @type {ol.MapBrowserEvent} * @api */ mapBrowserEvent: ol.MapBrowserEvent; - + } } @@ -5913,14 +5922,14 @@ declare module ol { * @param {ol.Coordinate} coordinate The event coordinate. */ constructor(type: ol.interaction.TranslateEventType, features: ol.Collection, coordinate: ol.Coordinate); - + /** * The features being translated. * @type {ol.Collection.} * @api */ features: ol.Collection; - + /** * The coordinate of the drag event. * @const @@ -5928,7 +5937,7 @@ declare module ol { * @api */ coordinate: ol.Coordinate; - + } } @@ -7845,18 +7854,18 @@ declare module ol { } - /** - * Register proj4. If not explicitly registered, it will be assumed that - * proj4js will be loaded in the global namespace. For example in a - * browserify ES6 environment you could use: - * - * import ol from 'openlayers'; - * import proj4 from 'proj4'; - * ol.proj.setProj4(proj4); - * - * @param {any} proj4 Proj4. - * @api - */ + /** + * Register proj4. If not explicitly registered, it will be assumed that + * proj4js will be loaded in the global namespace. For example in a + * browserify ES6 environment you could use: + * + * import ol from 'openlayers'; + * import proj4 from 'proj4'; + * ol.proj.setProj4(proj4); + * + * @param {any} proj4 Proj4. + * @api + */ function setProj4(proj4: any): void; /** @@ -8382,6 +8391,13 @@ declare module ol { */ getSource(): ol.source.Vector; + /** + * Get the distance in pixels between clusters. + * @return {number} The distance in pixels. + * @api + */ + getDistance(): number; + /** * Set the distance in pixels between clusters. * @param {number} distance The distance in pixels. @@ -10623,7 +10639,7 @@ declare module ol { * @param {ol.style.Fill} fill Fill style. * @api */ - setFill(fill: ol.style.Fill):void; + setFill(fill: ol.style.Fill): void; /** * Set a geometry that is rendered instead of the feature's geometry. @@ -11789,6 +11805,20 @@ declare module ol { */ setRotation(rotation: number): void; + /** + * Set a new maximum zoom level for the view. + * @param {number} zoom The maximum zoom level. + * @api stable + */ + setMaxZoom(zoom: number): void; + + /** + * Set a new minimum zoom level for the view. + * @param {number} zoom The minimum zoom level. + * @api stable + */ + setMinZoom(zoom: number): void; + /** * Zoom to a specific zoom level. * @param {number} zoom Zoom level. @@ -11803,7 +11833,7 @@ declare module ol { * @param {olx.AnimateOptions | (completed: boolean) => void } restArgs * @api experimental */ - animate(...var_args: Array): void; + animate(...var_args: Array): void; } @@ -12358,6 +12388,7 @@ declare module olx { interface DefaultsOptions { altShiftDragRotate?: boolean; doubleClickZoom?: boolean; + constrainResolution?: boolean; keyboard?: boolean; mouseWheelZoom?: boolean; shiftDragZoom?: boolean; @@ -12461,6 +12492,7 @@ declare module olx { * geometryName: (string|undefined), * condition: (ol.EventsConditionType|undefined), * freehandCondition: (ol.EventsConditionType|undefined), + * freehand: (boolean|undefined) * wrapX: (boolean|undefined)}} */ interface DrawOptions { @@ -12477,6 +12509,7 @@ declare module olx { geometryName?: string; condition?: ol.EventsConditionType; freehandCondition?: ol.EventsConditionType; + freehand?: boolean; wrapX?: boolean; } diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index ca74a6bbc2..de12feeb80 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -64,6 +64,7 @@ let styleArray: Array; let styleFunction: ol.StyleFunction; let tilegrid: ol.tilegrid.TileGrid; let transformFn: ol.TransformFunction; +let clusterSource: ol.source.Cluster; let vectorSource: ol.source.Vector; let units: ol.proj.Units; let styleRegularShape: ol.style.RegularShape; @@ -350,6 +351,13 @@ featureCollection = vectorSource.getFeaturesCollection(); featureArray = vectorSource.getFeaturesInExtent(extent); voidValue = vectorSource.removeFeature(feature); + +clusterSource = new ol.source.Cluster({ + source: vectorSource +}); + +numberValue = clusterSource.getDistance(); + // // ol.Feature // @@ -386,6 +394,9 @@ let view: ol.View = new ol.View({ zoom: numberValue, }); +voidValue = view.setMaxZoom(numberValue); +voidValue = view.setMinZoom(numberValue); + // // ol.layer.Tile // @@ -418,10 +429,10 @@ voidValue = olObject.unset(stringValue, booleanValue); ol.Observable.unByKey(eventKey); let observable: ol.Observable = new ol.Observable(); voidValue = observable.changed(); -voidOrBooleanValue = observable.dispatchEvent({type: stringValue}); -voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: domEventTarget}); -voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: eventTarget}); -voidOrBooleanValue = observable.dispatchEvent({type: stringValue, a: numberValue, b: stringValue, c: booleanValue, d: null, e: {}}); +voidOrBooleanValue = observable.dispatchEvent({ type: stringValue }); +voidOrBooleanValue = observable.dispatchEvent({ type: stringValue, target: domEventTarget }); +voidOrBooleanValue = observable.dispatchEvent({ type: stringValue, target: eventTarget }); +voidOrBooleanValue = observable.dispatchEvent({ type: stringValue, a: numberValue, b: stringValue, c: booleanValue, d: null, e: {} }); voidOrBooleanValue = observable.dispatchEvent(olEvent); voidOrBooleanValue = observable.dispatchEvent(stringValue); numberValue = observable.getRevision(); @@ -437,7 +448,7 @@ voidValue = observable.un([stringValue, stringValue], fn, {}); // let getPointResolutionFn: (n: number, c: ol.Coordinate) => number; projection = new ol.proj.Projection({ - code:stringValue, + code: stringValue, }); stringValue = projection.getCode(); extent = projection.getExtent(); @@ -468,7 +479,7 @@ let imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ params: {}, projection: projection, serverType: stringValue, - url:stringValue + url: stringValue }); // @@ -484,7 +495,7 @@ let tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ params: {}, projection: projection, serverType: stringValue, - url:stringValue + url: stringValue }); voidValue = tileWMS.updateParams(tileWMS.getParams()); @@ -657,12 +668,22 @@ draw = new ol.interaction.Draw({ type: "Point", style: styleFunction }); -let styleFunctionAsStyle = function(feature: ol.Feature, resolution: number): ol.style.Style { return style; } +let styleFunctionAsStyle = function (feature: ol.Feature, resolution: number): ol.style.Style { return style; } draw = new ol.interaction.Draw({ type: "Point", style: styleFunctionAsStyle }); -let styleFunctionAsArray = function(feature: ol.Feature, resolution: number): ol.style.Style[] { return styleArray; } +ol.interaction.Draw.createBox(); +ol.interaction.Draw.createRegularPolygon(); +ol.interaction.Draw.createRegularPolygon(4); +ol.interaction.Draw.createRegularPolygon(4, 0); + +ol.interaction.defaults({ + constrainResolution: booleanValue +}); + + +let styleFunctionAsArray = function (feature: ol.Feature, resolution: number): ol.style.Style[] { return styleArray; } draw = new ol.interaction.Draw({ type: "Point", style: styleFunctionAsArray @@ -699,7 +720,7 @@ const select: ol.interaction.Select = new ol.interaction.Select({ // styleRegularShape = new ol.style.RegularShape({ - fill: new ol.style.Fill({color: 'red'}), + fill: new ol.style.Fill({ color: 'red' }), points: 4, }); diff --git a/types/openlayers/v3/index.d.ts b/types/openlayers/v3/index.d.ts new file mode 100644 index 0000000000..c9791bc109 --- /dev/null +++ b/types/openlayers/v3/index.d.ts @@ -0,0 +1,13931 @@ +// Type definitions for OpenLayers v3.20.0 +// Project: http://openlayers.org/ +// Definitions by: Olivier Sechet , Matthias Dailey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) + +declare type GlobalObject = Object; + +/** + * @namespace ol + */ +declare module ol { + /** + * The animation static methods are designed to be used with the + * {@link ol.Map#beforeRender} method. For example: + * + * var map = new ol.Map({ ... }); + * var zoom = ol.animation.zoom({ + * resolution: map.getView().getResolution() + * }); + * map.beforeRender(zoom); + * map.getView().setResolution(map.getView().getResolution() * 2); + * + * @namespace ol.animation + */ + module animation { + /** + * Generate an animated transition that will "bounce" the resolution as it + * approaches the final value. + * @param {olx.animation.BounceOptions} options Bounce options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param {olx.animation.PanOptions} options Pan options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param {olx.animation.RotateOptions} options Rotate options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param {olx.animation.ZoomOptions} options Zoom options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + + } + + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + class AssertionError extends Error { + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + constructor(code: number); + + /** + * Error code. The meaning of the code can be found on + * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with + * the version found in the OpenLayers script's header comment if a version + * other than the latest is used). + * @type {number} + * @api + */ + code: number; + + } + + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + class Attribution { + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @return {string} The attribution HTML. + * @api stable + */ + getHTML(): string; + + } + + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + class Collection extends ol.Object { + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + constructor(opt_array?: T[]); + + /** + * Remove all elements from the collection. + * @api stable + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array.} arr Array. + * @return {ol.Collection.} This collection. + * @api stable + */ + extend(arr: T[]): ol.Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param {function(this: S, T, number, Array.): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @param {S=} opt_this The object to use as `this` in `f`. + * @template S + * @api stable + */ + forEach(f: ((item: T, index: number, array: T[]) => any), opt_this?: S): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array.} Array. + * @api stable + */ + getArray(): T[]; + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api stable + */ + item(index: number): T; + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api stable + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + insertAt(index: number, elem: T): void; + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api stable + */ + pop(): (T); + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} Length. + * @api stable + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api stable + */ + remove(elem: T): (T); + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api stable + */ + removeAt(index: number): (T); + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + setAt(index: number, elem: T): void; + + } + + module Collection { + + type EventType = string; + + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + constructor(type: ol.Collection.EventType, opt_element?: any); + + /** + * The element that is added to or removed from the collection. + * @type {*} + * @api stable + */ + element: any; + + } + } + + /** + * Colors can be defined as a {@link ol.Color} array, or as strings in + * `rgb(r,g,b)` or `rgba(r,g,b,a)` format, or in hex `#rrggbb` or `#rgb` format. + * Color names, like 'red', 'blue' or 'green', may also be used with the + * Canvas renderer. + * + * @namespace ol.color + */ + module color { + /** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {ol.Color|string} color Color. + * @return {ol.Color} Color. + * @api + */ + function asArray(color: (ol.Color | string)): ol.Color; + + /** + * Return the color as an rgba string. + * @param {ol.Color|string} color Color. + * @return {string} Rgba string. + * @api + */ + function asString(color: (ol.Color | string)): string; + + } + + /** + * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by + * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). + * @namespace ol.colorlike + */ + module colorlike { + /** + * @param {ol.Color|ol.ColorLike} color Color. + * @return {ol.ColorLike} The color as an ol.ColorLike + * @api + */ + function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; + + } + + /** + * @namespace ol.control + */ + module control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + class Attribution extends ol.control.Control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + constructor(opt_options?: olx.control.AttributionOptions); + + /** + * Update the attribution element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Attribution} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + } + + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + class Control extends ol.Object { + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + * @return {ol.Map} Map. + * @api stable + */ + getMap(): ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {ol.Map} map Map. + * @api stable + */ + setMap(map: ol.Map): void; + + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {Element|string} target Target. + * @api + */ + setTarget(target: (Element | string)): void; + + } + + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + class FullScreen extends ol.control.Control { + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.FullScreenOptions); + + } + + /** + * Set of controls included in maps by default. Unless configured otherwise, + * this returns a collection containing an instance of each of the following + * controls: + * * {@link ol.control.Zoom} + * * {@link ol.control.Rotate} + * * {@link ol.control.Attribution} + * + * @param {olx.control.DefaultsOptions=} opt_options Defaults options. + * @return {ol.Collection.} Controls. + * @api stable + */ + function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + class MousePosition extends ol.control.Control { + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + constructor(opt_options?: olx.control.MousePositionOptions); + + /** + * Update the mouseposition element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.MousePosition} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return the coordinate format type used to render the current position or + * undefined. + * @return {ol.CoordinateFormatType|undefined} The format to render the current + * position in. + * @observable + * @api stable + */ + getCoordinateFormat(): (ol.CoordinateFormatType); + + /** + * Return the projection that is used to report the mouse position. + * @return {ol.proj.Projection|undefined} The projection to report mouse + * position in. + * @observable + * @api stable + */ + getProjection(): (ol.proj.Projection); + + /** + * Set the coordinate format type used to render the current position. + * @param {ol.CoordinateFormatType} format The format to render the current + * position in. + * @observable + * @api stable + */ + setCoordinateFormat(format: ol.CoordinateFormatType): void; + + /** + * Set the projection that is used to report the mouse position. + * @param {ol.proj.Projection} projection The projection to report mouse + * position in. + * @observable + * @api stable + */ + setProjection(projection: ol.proj.Projection): void; + + } + + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + class OverviewMap extends ol.control.Control { + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + constructor(opt_options?: olx.control.OverviewMapOptions); + + /** + * Update the overview map element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.OverviewMap} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the overview map is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the overview map should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the overview map according to the passed parameter. Will + * not do anything if the overview map isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Determine if the overview map is collapsed. + * @return {boolean} The overview map is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + /** + * Return the overview map. + * @return {ol.Map} Overview map. + * @api + */ + getOverviewMap(): ol.Map; + + } + + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + class Rotate extends ol.control.Control { + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + constructor(opt_options?: olx.control.RotateOptions); + + /** + * Update the rotate control element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Rotate} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + class ScaleLine extends ol.control.Control { + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + constructor(opt_options?: olx.control.ScaleLineOptions); + + /** + * Return the units to use in the scale line. + * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * line. + * @observable + * @api stable + */ + getUnits(): (ol.control.ScaleLine.Units); + + /** + * Update the scale line element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ScaleLine} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Set the units to use in the scale line. + * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @observable + * @api stable + */ + setUnits(units: ol.control.ScaleLine.Units): void; + } + + module ScaleLine { + /** + * @enum {string} + * @api + */ + type Property = string; + + /** + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + * @enum {string} + */ + type Units = "degrees" | "imperial" | "nautical" | "metric" | "us"; + } + + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + class Zoom extends ol.control.Control { + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomOptions); + + } + + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + class ZoomSlider extends ol.control.Control { + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomSliderOptions); + + /** + * Update the zoomslider element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ZoomSlider} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + class ZoomToExtent extends ol.control.Control { + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomToExtentOptions); + + } + + } + + /** + * @namespace ol.coordinate + */ + module coordinate { + /** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * ol.coordinate.add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {ol.Coordinate} delta Delta. + * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @api stable + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a {@link ol.CoordinateFormatType} function that can be used to format + * a {ol.Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(); + * var out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(2); + * var out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {ol.CoordinateFormatType} Coordinate format. + * @api stable + */ + function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given {@link ol.Coordinate} to a string using the given string + * template. The strings `{x}` and `{y}` in the template will be replaced with + * the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api stable + */ + function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; + + /** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * var rotateRadians = Math.PI / 2; // 90 degrees + * ol.coordinate.rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {ol.Coordinate} Coordinate. + * @api stable + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api stable + */ + function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + /** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api stable + */ + function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + } + + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + class DeviceOrientation extends ol.Object { + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + constructor(opt_options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ + getAlpha(): (number); + + /** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ + getBeta(): (number); + + /** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ + getGamma(): (number); + + /** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ + getHeading(): (number); + + /** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ + setTracking(tracking: boolean): void; + + } + + /** + * Objects that need to clean up after themselves. + * @constructor + */ + class Disposable { + /** + * Objects that need to clean up after themselves. + * @constructor + */ + constructor(); + + } + + /** + * Easing functions for {@link ol.animation}. + * @namespace ol.easing + */ + module easing { + /** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown + * is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function upAndDown(t: number): number; + + } + + /** + * Applications do not normally create event instances. They register (and + * unregister) event listener functions, which, when called by the library as + * the result of an event being dispatched, are passed event instances as their + * first argument. Listeners can be registered and unregistered on all objects + * descending from {@link ol.Observable}. All event instances have a `target` + * property, which corresponds to the object on which the event was dispatched. + * By default, `this` within the listener also refers to the target, though + * this can be configured in the listener registration function. + * Some classes have their own event type, which return additional + * properties; see the specific event class page for details. + * + * @namespace ol.events + */ + module events { + /** + * @namespace ol.events.condition + */ + module condition { + /** + * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when + * additionally the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt key is pressed. + * @api stable + */ + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise + * (e.g. when additionally the platform-modifier-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt and shift keys are pressed. + * @api stable + */ + function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always true. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True. + * @function + * @api stable + */ + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a `click` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `click` event. + * @api stable + */ + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always false. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} False. + * @function + * @api stable + */ + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the browser event is a `pointermove` event, `false` + * otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the browser event is a `pointermove` event. + * @api + */ + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `singleclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `singleclick` event. + * @api stable + */ + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `dblclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `dblclick` event. + * @api stable + */ + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is + * pressed. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True only if there no modifier keys are pressed. + * @api stable + */ + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the platform-modifier-key (the meta-key on Mac, + * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally + * the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the platform modifier key is pressed. + * @api stable + */ + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when + * additionally the alt-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the shift key is pressed. + * @api stable + */ + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the target element is not editable, i.e. not a ``-, + * `